链接: 直达地在这里
为了水字数,我还是把题目放在这里了:
给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。
假设二叉树中至少有一个节点.
思考如下:
1.我们要找的是最底层最左边节点的值嘛,那么如何确定这个节点符合最低层最左边节点的值呢?
2.提取关键词:最底层,最左边.
思路如下:
思路1最底层最左边:可以使用层序遍历来解决,无非就是当我们遍历(同时保证单层元素遍历方向是从左到右)时把第一个遍历的节点弹出作为最终的返回值.
思路2最底层最左边:也可以通过递归来啊,通过求深度的前序遍历(这和上面一样间接保证了单层元素的遍历方向是从左向右)来解决嘛,然后如果他的
深度是大于我们当前保存深度最大的节点,则让新值覆盖旧值.
答应我,都看到这了,给个点赞,收藏吧(然后先去试着做一遍,再来看我的代码)
第一种:
class Solution {
public int findBottomLeftValue(TreeNode root) {
//目测:这题也就是层序遍历,结合前序遍历而已
//直接用迭代的前序遍历应该也可以,就比较一下深度就ok
if(root==null)return 0;
Queue<TreeNode> nodes=new LinkedList<>();
nodes.offer(root);
int res=0;//这边随便给值了,反正至少会被覆盖
while(!nodes.isEmpty()){
int size=nodes.size();
TreeNode tem=nodes.poll();
res=tem.val;
if(tem.left!=null)nodes.offer(tem.left);
if(tem.right!=null)nodes.offer(tem.right);
for (int i = 1; i < size; i++) {
tem=nodes.poll();
if(tem.left!=null)nodes.offer(tem.left);
if(tem.right!=null)nodes.offer(tem.right);
}
}
return res;
}
}
第二种
class Solution {
int res=0;
int MaxDepth=0;
public int findBottomLeftValue(TreeNode root) {
//目标是递归玩法:
//什么序其实都可以,这里使用前序遍历
//中左右
//1.递归函数的参数与返回值
//参数root,depth,返回值void
//2.退出条件
//当root.left&&root.right==null
//3.单层递归的实现逻辑
if(root==null)return 0;
res=root.val;
getLeftValue(root,0);
return res;
}
public void getLeftValue(TreeNode root,int depth){
if(root.left==null&&root.right==null){
if(depth>MaxDepth){
res= root.val;
MaxDepth=depth;
}
return;
}
//中
//左
if(root.left!=null){
getLeftValue(root.left,depth+1);
}
//右
if(root.right!=null){
getLeftValue(root.right,depth+1);
}
}
}