Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created August 30, 2014 05:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiren-wang/1c52632f6a92616c3944 to your computer and use it in GitHub Desktop.
Save xiren-wang/1c52632f6a92616c3944 to your computer and use it in GitHub Desktop.
max depth of binary tree
/**
* 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