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

Example 1:

Input:
    2
   / \
  1   3

Output:
1

Example 2:

Input:
        1
       / \
      2   3
     /   / \
    4   5   6
       /
      7

Output:
7

Solution: 按层遍历,找到最底层的最左

    public int findBottomLeftValue(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode ans = root;
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            ans = queue.peek();
            for(int i = 0; i < size; i++){
                TreeNode curt = queue.poll();
                if(curt.left != null){
                    queue.offer(curt.left);
                }
                if(curt.right != null){
                    queue.offer(curt.right);
                }
            }
        }
        return ans.val;
    }

results matching ""

    No results matching ""