代码随想录:513. 找树左下角的值
513. 找树左下角的值
使用层序遍历,找到最后一层时输出即可
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
Deque<TreeNode> q=new LinkedList<>();
q.add(root);
TreeNode last=root;
int sum=0;
TreeNode head=root;
while(!q.isEmpty())
{
TreeNode cur=q.poll();
if(cur.left!=null){q.add(cur.left);sum++;}
if(cur.right!=null){q.add(cur.right);sum++;}
if(cur==last)
{
if(sum==0)
{
return head.val;
}
sum=0;
head=q.peekFirst();
last=q.peekLast();
}
}
return 0;
}
}