Created
August 30, 2014 05:41
-
-
Save xiren-wang/1c52632f6a92616c3944 to your computer and use it in GitHub Desktop.
max depth of binary tree
This file contains 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) {} | |
* }; | |
* | |
* The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. | |
*/ | |
class Solution { | |
public: | |
int maxDepth(TreeNode *root) { | |
// max depth is this level (if present) plus max of its two sub-trees | |
if (!root) | |
return 0; | |
return 1 + max(maxDepth(root->left), maxDepth(root->right)); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment