lC - 104. 二叉树的最大深度
难度:简单
题目描述
难度简单877收藏分享切换为英文接收动态反馈
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
示例:
给定二叉树 [3,9,20,null,null,15,7]
,
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
MyCode
/**
* 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 == nullptr) return 0;
else if(root->left == nullptr && root->right == nullptr) return 1;
else if(root->left != nullptr && root->right == nullptr)
return maxDepth(root->left) + 1;
else if(root->left == nullptr && root->right != nullptr)
return maxDepth(root->right) + 1;
else return std::max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
复杂度分析
-
时间复杂度:O(n),遍历二叉树所有元素就行
-
空间复杂度:O(hegiht),递归需要递归调用栈存储临时变量
TaCode
深度优先搜索
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};
复杂度分析
- 时间复杂度:O*(*n),其中 n 为二叉树节点的个数。每个节点在递归中只被遍历一次。
- 空间复杂度:O*(*height),其中height 表示二叉树的高度。递归函数需要栈空间,而栈空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。