题目描述
给定一个二叉树,找出其最大深度。
二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。
说明: 叶子节点是指没有子节点的节点。
题解
题解1:递归
以下内容来自求树的最大深度(详解)和代码随想录微信公众号。
递归三部曲:
- 确定递归函数的参数和返回值: 参数就是传入树的根节点,返回这棵树的深度,返回值为int类型。
int getDepth(TreeNode* node)
- 确定终止条件:如果为空节点的话,就返回0,表示高度为0。
if (node == NULL) return 0;
- 确定单层递归的逻辑:先求它的左子树的深度,再求的右子树的深度,最后取左右深度最大的数值 再+1 (加1是因为算上当前中间节点)就是目前节点为根节点的树的深度。
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
int depth = 1 + max(leftDepth, rightDepth); // 中
return depth;
/**
* 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 getDepth(TreeNode *node){
if(node == NULL) return 0;
int leftDepth = getDepth(node->left);
int rightDepth = getDepth(node->right);
int depth = 1 + max(leftDepth,rightDepth);
return depth;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
复杂度分析
- 时间复杂度:O(n),其中 n 为二叉树节点的个数。每个节点在递归中只被遍历一次。
- 空间复杂度:O(height),其中 height 表示二叉树的高度。递归函数需要栈空间,而队列空间取决于递归的深度,因此空间复杂度等价于二叉树的高度。
题解2:宽度优先搜索(BFS)
层序遍历, 每一层从左到右, 记录下二叉树的深度。
/**
* 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 == NULL) return 0;
int depth = 0;
queue<TreeNode*> que;
que.push(root);
while(!que.empty()) {
int size = que.size();
depth++; // 记录深度
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return depth;
}
};
复杂度分析
- 时间复杂度:O(n),其中 n 为二叉树的节点个数。
- 空间复杂度:此方法空间的消耗取决于队列存储的元素数量,其在最坏情况下会达到 O(n)。
参考(很重要,需复习)
求树的最大深度(详解)
二叉树:层序遍历登场!
关于二叉树,你该了解这些!
二叉树:总结篇!(需要掌握的二叉树技能都在这里了)
二叉树的最大深度
C++的三种方法实现(有注解)