BFS的变式 ,用一个result保存每一层的第一个就好了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int findBottomLeftValue(TreeNode root) {
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
queue.add(root);
int result = 0 ;
while(!queue.isEmpty())
{
int size = queue.size();
result = queue.peek().val;
for(int i = 0 ;i<size;i++)
{
TreeNode node = queue.poll();
if(node.left!=null)
queue.add(node.left);
if(node.right!=null)
queue.add(node.right);
}
}
return result ;
}
}
网友评论