Leetcode513.找出树的左下角的值_数据结构
解题思路
题目要求的值肯定是在最后一层上,这是肯定的。 所以我们只需要找到最后一层的节点。然后再想办法就行。

那么对于这么一棵树,咱们层序遍历的话,其实可以从树的右子树开始遍历,再遍历左子树,那么咱们在队列出队的最后一个元素的时候, 就是咱们要找的最深一层的最左边的一个元素的。
有没有感觉,对于这个题来说,广度优先算法,更加容易和适合

代码如下:

class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
root = queue.poll();
if (root.right != null) queue.offer(root.right);
if (root.left != null) queue.offer(root.left);
}
return root.val;
}
}