【leetcode】513.Find Bottom Left Tree Value

原題

Given a binary tree, find the leftmost value in the last row of the tree.node

Example 1:
Input:code

2
/ 1 3ast

Output:
1
Example 2:
Input:List

1
       / \
      2   3
    /    / \
  4    5   6
/

7搜索

Output:
7
Note: You may assume the tree (i.e., the given root node) is not NULL.queue

解析

查找最後一層最左側的葉子節點的值while

思路

BFS,從右向左搜索co

解法(同最優解)

public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode last = root;
        queue.offer(root);
        while (!queue.isEmpty()) {
            last = queue.poll();
            if (last.right != null) {
                queue.offer(last.right);
            }
            if (last.left != null) {
                queue.offer(last.left);
            }
        }
        return last.val;
    }
相關文章
相關標籤/搜索