Question
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.
Note: A leaf is a node with no children.
Difficulty:Easy
Category:Tree, Depth-first-Search
Analyze
This is a easy question for the tree problem. This question have these feature:
- One root node question
- We can use the return value to compare.
So we use the template code for the Tree Question
.
There are four steps for this template:
- Boundary conditions.
- Deal with the root value.
- recursive call funciton
- compare ouput value
Post: Tree Question Summary
Solution
/**
* 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 == nullptr) return 0;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return max(l, r) + 1;
}
};