一、前言:
参考文献:代码随想录
今天的题目是昨天层序遍历的递归版本,从对栈和队列的应用转到更加简便的递归操作,是非常有助于对栈堆的理解的。
二、二叉树的最大深度:
1、思路:
这个题目如果用昨天的层序遍历的话,是非常方便的,只需要套用模板,每遍历一层就可以让深度加1,即可完成深度的统计。
递归的思路就是
(1)先确定返回值和参数:返回深度(int)参数root(TreeNode*)
(2)确定终止条件:这里比较简单就是root==NULL 就终止了
(3)递归顺序,这里可以用前序遍历或者后序遍历,只需要找出左子树和右子树其中的最大深度即可,在每次找到后深度加一,可以得到递增的depth。
2、后序遍历代码:
private:
int deep(TreeNode* node) {
if(node == NULL) {
return 0;
}
int leftdepth = deep(node->left); // 左
int rightdepth = deep(node->right); // 右
return (1 + max(leftdepth, rightdepth)); // 中,返回左边和右边中的最大值
}
public:
int maxDepth(TreeNode* root) {
return deep(root);
}
3、前序遍历代码(涉及回溯):
class Solution {
private:
int result;
// 利用前序遍历来测量二叉树的最大深度
void getDepth(TreeNode* node, int depth) {
// 存最大的数值
result = depth > result ? depth : result;
if (node->left == NULL && node->right == NULL) {
return; // 遍历到最后的节点,往回走。
}
// 左
if (node->left) {
getDepth(node->left, depth + 1); // 深度加一,但是不需要“++”,因为这个需要回溯的
}
// 右
if (node->right) {
getDepth(node->right, depth + 1);
}
return;
}
public:
int maxDepth(TreeNode* root) {
result = 0;
if (root == NULL) return 0;
getDepth(root, 1);
return result;
}
};
三、二叉树的最小深度:
1、思路:
昨天用队列写了一遍,今天就需要用递归了,还是递归三部曲走起:
(1)这里返回值是int,返回一个深度。
(2)终止条件就node为NULL即可
(3)传入参数需要传入node去寻找最小子树。
(4)大结构的话就可以是后序遍历了,可以先查看左右子树是否为空在看是否往下走。
2、代码:
class Solution {
private:
int result;
int getMinDepth(TreeNode* node) {
if (node == NULL) return 0;
// 左
int left = getMinDepth(node->left);
// 右
int right = getMinDepth(node->right);
// 中
// 右子树为空,左子树不为空,说明这不为最低点
if (node->left != NULL && node->right == NULL) {
return 1 + left;
}
// 同理
if (node->right != NULL && node->left == NULL) {
return 1 + right;
}
result = 1 + min(left, right);
return result;
}
public:
int minDepth(TreeNode* root) {
result = 0;
return getMinDepth(root);
//result;
}
};
四、完全二叉树的节点个数:
1、思路:
首先这是一个递归,那就去选择递归三部曲:
(1)返回值是一个int 返回深度;
(2)传入参数为左右的深度,还有一个节点;
(3)终止条件为if(node == NULL);
(4)使用的是后序遍历,先处理左右子树长度,在统计左右子树的长度;
2、代码:
class Solution {
private:
int depth;
int TreeSize(TreeNode* node, int num) {
if (node == NULL) return 0;
int left = TreeSize(node->left, num + 1);
int right = TreeSize(node->right, num + 1);
depth = 1 + left + right;
return depth;
}
public:
int countNodes(TreeNode* root) {
depth = 0;
if (root == NULL) return 0;
TreeSize(root, 1);
return depth;
}
};
但是,貌似我多此一举了,我多设置了一个num来计算左右子树的深度,貌似没什么用。
4、修改后的代码:
class Solution {
private:
int depth;
int TreeSize(TreeNode* node) {
if (node == NULL) return 0;
int left = TreeSize(node->left);
int right = TreeSize(node->right);
depth = 1 + left + right;
return depth;
}
public:
int countNodes(TreeNode* root) {
depth = 0;
if (root == NULL) return 0;
TreeSize(root);
return depth;
}
};
今日学习时间一个半小时;
leave message:
Twenty years from now you will be more disappointed by the things thet you didn't do than by the ones you did do.