领扣(LeetCode)找树左下角的值 个人题解

给定一个二叉树,在树的最后一行找到最左边的值。

示例 1:

输入:

    2
   / 
  1   3

输出:
1

示例 2:

输入:

        1
       / 
      2   3
     /   / 
    4   5   6
       /
      7

输出:
7

注意: 您可以假设树(即给定的根节点)不为 NULL。

这题呢,根据题意,采取层级遍历的方式。用一个队列来存放当前层的所有节点,始终设置层级遍历完之后,队列中最左边的节点的值为我们需要的答案,一直遍历到最后一层,得到正确答案。效率尚可。

代码如下:

 1 class Solution {
 2     public int findBottomLeftValue(TreeNode root) {
 3         int ans = root.val;
 4         Queue<TreeNode> queue = new ArrayDeque<>();
 5         queue.add(root);
 6         while (!queue.isEmpty()) {
 7             ans = queue.peek().val;
 8             Queue<TreeNode> tmp = new ArrayDeque<>();
 9             while (!queue.isEmpty()) {
10                 TreeNode ttmp = queue.poll();
11                 if (ttmp.left != null)
12                     tmp.add(ttmp.left);
13                 if (ttmp.right != null)
14                     tmp.add(ttmp.right);
15             }
16             queue = tmp;
17         }
18         return ans;
19     }
20 }
原文地址:https://www.cnblogs.com/axiangcoding/p/10013327.html