Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example: Given binary tree [3,9,20,null,null,15,7],
3 / \ 9 20 / \ 15 7
return its depth = 3.
Solution: Bottom-Up
int maxDepth(TreeNode* root) {
if(!root) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
Solution: Top-Down
void helper(TreeNode *root, int depth, int &maxDepth) {
if (!root) return;
if (!root->left && !root->right) maxDepth = max(depth, maxDepth);
if (root->left) helper(root->left, depth+1, maxDepth);
if (root->right) helper(root->right, depth+1, maxDepth);
}
int maxDepth(TreeNode* root) {
if (!root) return 0;
int maxDepth = 0;
helper(root, 0, maxDepth);
return maxDepth;
}