Depth-first-search - Easy Level - Question 1
Leetcode104. Maximum Depth of Binary Tree
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Constraints:
The number of nodes in the tree is in the range [0, 10^4].
-100 <= Node.val <= 100
Analysis:
A binary tree has a recursive structure in nature: the left child is the root of the sub binary tree on the left; the right child is the root of the sub binary tree on the right.
So we can apply DFS to this question:
1. the base cases: if the node is null, return 0; if not
2. the maximum depth should be 1 + max(Maximum Depth of the left sub tree, Maximum Depth of the right sub tree).
See the code below:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
Note: pay attention to the definition of the TreeNode, which can be used when need to write your own struct (for example, in the Trie)
Comments
Post a Comment