题目
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例
题解
一.DFS depth first search
1.1思路
如题目所示
1.2复杂度
时间:O(n);
空间:O(n);
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root==NULL)
return 0;
else
{
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
}
};
超简洁版
class Solution {
public:
int maxDepth(TreeNode* root, int i = 0) {
return root ? max(maxDepth(root->left, ++i) ,maxDepth(root->right, i)) : i;
}
};
作者:yi-ke-da-bai-tu
链接:https://leetcode-cn.com/problems/maximum-depth-of-binary-tree/solution/3xing-dai-ma-shuang-100-by-yi-ke-da-bai-vhdyp/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。