Skip to content

Instantly share code, notes, and snippets.

@kyunghoj
Created September 22, 2016 13:33
Show Gist options
  • Save kyunghoj/e3901303c6e3133455cd1bd01b1027f9 to your computer and use it in GitHub Desktop.
Save kyunghoj/e3901303c6e3133455cd1bd01b1027f9 to your computer and use it in GitHub Desktop.
[codelab] Given a binary tree, find its maximum depth.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode *root) {
// Corner case. Should never be hit unless the code is called on root = NULL
if (root == NULL) return 0;
// Base case : Leaf node. This accounts for height = 1.
if (root->left == NULL && root->right == NULL) return 1;
if (!root->left) return maxDepth(root->right) + 1;
if (!root->right) return maxDepth(root->left) + 1;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
/**
* Definition for binary tree
* class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public int maxDepth(TreeNode a) {
if (a == null) {
return 0;
}
int leftDepth = maxDepth(a.left) + 1;
int rightDepth = maxDepth(a.right) + 1;
return java.lang.Math.max (leftDepth, rightDepth);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment