1,题目要求
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.
给定二叉树,找到它的最大深度。
最大深度是从根节点到最远叶节点的最长路径上的节点数。
注意:叶子是没有子节点的节点。
2,题目思路
对于这道题,也是属于树的题目。题目要求求得一棵树的最大深度,利用递归的方法,可以很方便的求得深度。
3,代码实现
static auto speedup = [](){
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr)
return 0;
return max(maxDepth(root->left), maxDepth(root->right))+1;
}
};