Created
September 22, 2016 13:33
-
-
Save kyunghoj/e3901303c6e3133455cd1bd01b1027f9 to your computer and use it in GitHub Desktop.
[codelab] Given a binary tree, find its maximum depth.
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 | |
* 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; | |
} | |
}; |
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 | |
* 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