513.找左下角的值
思路
1.层序遍历做这题比较好做,定义一个变量值为根节点值,后续每循环一层,将值更改为队列的peek值。最后输出。
2.还有一种深搜递归,设置两个全局变量,一个用于记录当前的值,一个用于记录该值在树的层数。深搜遍历采用前序遍历,若深度大于该值,则替换,这样一来会记录深度最大的值,由于采用前序遍历,第一个深度最大的值一定为最左边的值,后续深度相同的值无法替换。
代码
1.层序
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue=new ArrayDeque<>();
queue.offer(root);
int size=queue.size();
int minleft=root.val;
while (!queue.isEmpty()){
while (size>0){
TreeNode node=queue.poll();
if (node.left!=null) queue.offer(node.left);
if (node.right!=null) queue.offer(node.right);
size--;
}
size=queue.size();
if (queue.peek() != null) {
minleft=queue.peek().val;
}
}
return minleft;
}
}
2.深搜
int minleft,max=0;
public int findBottomLeftValue(TreeNode root) {
getMinleft(root,1);
return minleft;
}
public void getMinleft(TreeNode root,int depth) {
if (root==null) return ;
if (depth>max) {
minleft=root.val;
max=depth;
}
getMinleft(root.left,depth+1);
getMinleft(root.right,depth+1);
return;
}