求二叉树左下角的值
给定一个二叉树,在树的最后一行找到最左边的值
分析:遍历整个树时候用void方法配合全局变量,递归遍历部分时候需要返回值
#include "_myPrint.cpp"
#include "stack"
#include "queue"
using namespace std;
// 找到二叉树中左下角的值
// 左下角为最深一层最左边的值
class Solution{
public:
// 确定递归的参数和返回值
// 确定每一层递归需要做的事情
// 确定递归的终止条件
// 递归方法:前序能保证先遍历到左边 如何保证是最深一层?
// 可以保存深度 每当遍历到左侧叶子节点 计算一下深度 并和之前的深度做比较 如果更深就覆盖
// 需要遍历一整棵树 所以需要回溯 所以函数没有返回值 并不是局部传递值
int maxDepth = INT_MIN; // 左叶子节点的深度
int res; // 左叶子节点的值
void leftBottom(TreeNode* root, int leftDepth){
// 无需判断是不是左节点了 只需要判断是否是叶子节点
// 前序总是先遍历左节点 如果深度最大就更新 再次遇到右兄弟节点深度一样大不会再更新
if (!root -> left && !root -> right){
if (leftDepth > maxDepth){
maxDepth = leftDepth;
res = root -> val;
}
return;
}
if (root -> left){
leftDepth++;
leftBottom(root -> left, leftDepth);
leftDepth--; // trackback
}
// 等同于
// if (root -> left) leftBottom(root -> left, leftDepth + 1); 这里的leftDepth + 1作为参数 其本身并没有增加 也完成了回溯
if (root -> right){
leftDepth++;
leftBottom(root -> right, leftDepth);
leftDepth--; // trackback
}
return;
}
// 也可以使用层序遍历的方式 每一层的第一个数字不停覆盖结果即可
};
int main(){
Solution s;
TreeNode* root = new TreeNode(8);
TreeNode* l = new TreeNode(6);
TreeNode* r = new TreeNode(7);
TreeNode* lr = new TreeNode(9);
TreeNode* rl = new TreeNode(10);
root->left = l;
root->right = r;
l->right = lr;
r->left=rl;
s.leftBottom(root, 1);
cout << s.res << endl;
}