Skip to content

Instantly share code, notes, and snippets.

@dmnugent80
Last active August 29, 2015 14:15
Show Gist options
  • Save dmnugent80/e70840914e7d8a17f884 to your computer and use it in GitHub Desktop.
Save dmnugent80/e70840914e7d8a17f884 to your computer and use it in GitHub Desktop.
Get Max Depth of Binary Tree from root
/**
* 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