文章内容是自己刷leetcode题目的一些总结。
文章内容参考公众号: 代码随想录。
一.二叉树深度与高度的介绍
-
二叉树节点的深度:从根节点到该节点的层数距离
-
二叉树结点的高度:从该节点到最下层叶子节点的层数距离
那么可以知道根节点的高度就是二叉树的最大深度。
二.二叉树的最大深度
由上可知,二叉树的最大深度可以转化为根节点的高度问题。我们可以使用前序遍历来解决高度问题,处理逻辑是中左右,在中时,更新树的高度。
class Solution {
public:
int ans;
void getDepth(TreeNode* node, int depth) {
ans = depth > ans ? depth : ans; //中
//终止条件,遇到叶子节点(根节点的高度就是最大深度)
if(!node->left && !node->right) return ;
if(node->left) { //左
getDepth(node->left, depth + 1);
}
if(node->right) { //右
getDepth(node->right, depth + 1);
}
}
int maxDepth(TreeNode* root) {
//递归法:前序遍历
ans = 0;
if(root == nullptr) return ans;
getDepth(root, 1);
return ans;
}
};
三.二叉树的最小深度
注意最小深度是从根节点到最近叶子节点的最短路径上的节点数量,所以我们的终止条件就是遇到叶子节点。依旧使用前序遍历。
class Solution {
public:
int ans;
void getMinDepth(TreeNode* root, int depth) {
//终止条件:遇到叶子节点
if(root->left == nullptr && root->right == nullptr) {
//更新ans
ans = min(ans, depth);
return ;
}
//中:没有处理逻辑
if(root->left) getMinDepth(root->left, depth + 1); //左
if(root->right) getMinDepth(root->right, depth + 1); //右
return ;
}
int minDepth(TreeNode* root) {
//递归:前序遍历
if(root == nullptr) return 0;
ans = INT_MAX;
getMinDepth(root, 1);
return ans;
}
};
四.拓展:n叉树的最大深度
1.迭代写法
这里给出n叉树最大深度的迭代写法,每往下走一层,depth + 1。我们每次往队列中加入的元素,应该是当前节点的所有孩子。
class Solution {
public:
int maxDepth(Node* root) {
if(root == NULL) return 0;
int depth = 0;
queue<Node*> que;
que.push(root);
while(!que.empty()) {
int size = que.size();
depth ++;
for(int i = 0; i < size; i ++) {
Node* node = que.front();
que.pop();
for(int j = 0; j < node->children.size(); j ++) {
que.push(node->children[j]);
}
}
}
return depth;
}
};
2.递归写法
思路同上,要遍历所有孩子。
class Solution {
public:
int maxDepth(Node* root) {
//递归写法
if(root == nullptr) return 0;
int depth = 0;
for(int i = 0; i < root->children.size(); i ++) {//遍历所有孩子
depth = max(depth, maxDepth(root->children[i]));
}
return depth + 1;
}
};
五.总结
今天我们学习了二叉树的深度与高度的相关问题,了解到如何求解二叉树的最大深度与最小深度,最后增加了一个拓展问题:求n叉树的最大深度。
其实对于这些问题,递归法与迭代法都是可以完成的,我这里主要给出了递归法的形式,初学者掌握一种已经很棒了。