Last active
August 29, 2015 14:15
-
-
Save dmnugent80/e70840914e7d8a17f884 to your computer and use it in GitHub Desktop.
Get Max Depth of Binary Tree from root
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for binary tree | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
import java.lang.Math; | |
public class Solution { | |
public int maxDepth(TreeNode root) { | |
if (root == null) return 0; | |
return maxDepthHelper(root, 1); | |
} | |
public int maxDepthHelper(TreeNode node, int level){ | |
if (node.left == null && node.right == null){ | |
return level; | |
} | |
int left = 0; | |
int right = 0; | |
if (node.left != null) | |
left = maxDepthHelper(node.left, level + 1); | |
if (node.right != null) | |
right = maxDepthHelper(node.right, level + 1); | |
return Math.max(left, right); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment