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.
This can be solved by recursion. Giving the root of the tree, we need to check whether it’s NULL, if so, return 0;
else return 1 plus the max depth of the left subtree and the right subtree.
Yes, so we can draw a tree like
root
left right
ll lr NULL NULL
NULL NULL
we start by root, and root is not NULL, so go to calculate the depth of left and right, and for right, it’s child is NULL so it will return 0 +1 = 1, for left it’ll return 0 +1 +1 and be 2, so the depth will be max(2, 1)+1 = 3
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
else return max(maxDepth(root->left), maxDepth(root->right))+1;
}
};