快过年了,家里迎来送往的,也没什么时间刷题,加上最近组会也在看一些论文,所以三天没有刷题,今天把之前做的题看了一下,对二叉树的深度做一个总结。
题目
层序遍历
找出二叉树的最大深度和最小深度,其实这里使用递归的话,会稍微有一些麻烦,层序遍历时一个很好的解决方案。
最大深度部分的代码,其实只是在层序遍历的基础上
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;
}
};
最小深度和最大深度同理,其实只是需要增加一个判断,当遇到叶子节点,立刻返回
class Solution {
public:
int minDepth(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&& !node->right) return depth;// 增加了这一句
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return depth;
}
};
递归法--广度优先遍历
前序遍历的顺序是中-左-右,后序遍历是-左-右-中,因此常用前序求深度,后序求高度。
- 二叉树节点的深度:根节点到该节点的最长简单路径边的条数或节点数
- 二叉树节点的高度:该节点到叶子节点的最长简单简单路径的条数或节点数
我们需要知道的是,根节点的高度就是二叉树的最大深度, 前序求深度,后序求高度
前序遍历
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);
}
};
后序遍历
当然这一题 也可以使用前序遍历,我自己看下来是感觉使用了回溯法,每次进入getdepth函数后,先比较当前节点的深度(result)与已知最大值(result)进行比较,之后判断是否为叶子节点,叶子节点之间返回,之后,左递归,回溯(deep-1),右同理。
class solution {
public:
int result;
void getdepth(treenode* node, int depth) {
result = depth > result ? depth : result; // 中
if (node->left == NULL && node->right == NULL) return ;
if (node->left) { // 左
depth++; // 深度+1
getdepth(node->left, depth);
depth--; // 回溯,深度-1
}
if (node->right) { // 右
depth++; // 深度+1
getdepth(node->right, depth);
depth--; // 回溯,深度-1
}
return ;
}
int maxdepth(treenode* root) {
result = 0;
if (root == NULL) return result;
getdepth(root, 1);
return result;
}
};
后序
最后看下来,层序遍历最简单,后序遍历稍微难以理解一些。