领扣(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 }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步