LeetCode 513. Find Bottom Left Tree Value
Given a binary tree, find the leftmost value in the last row of the tree.
就是拿到最后一层的第一个元素。
这个元素是最左下角的元素,不是最左侧的元素。
如果想实现 其实也很简单 就是维护更新每一层的第一个元素。
class Solution {
public int findBottomLeftValue(TreeNode root) {
if (root == null) return -1;
Queue<TreeNode> queue = new LinkedList<>();
TreeNode cur = root;
queue.offer(cur);
int leftMost = -1;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
cur = queue.poll();
if (i == 0) leftMost = cur.val;
if (cur.left != null) queue.offer(cur.left);
if (cur.right != null) queue.offer(cur.right);
}
}
return leftMost;
}
}
but clearly that’s not even close to the word “smart”.
and this, is the smart way. and if you really think about it, this should be what a level order traverse should be. we used to use that size of each level just to make the output can be in the same list, as a matter of fact, it doesn’t change the order of each node we traversed.
and if we traverse from right to left for each level, then the last node we will traverse to will be the bottom left one.
class Solution {
public int findBottomLeftValue(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
root = queue.poll();
if (root.right != null)
queue.add(root.right); //add right node first
if (root.left != null)
queue.add(root.left);
}
return root.val;
}
}

浙公网安备 33010602011771号