zoukankan      html  css  js  c++  java
  • 领扣(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 }
  • 相关阅读:
    生成函数
    泰勒公式与牛顿迭代
    如何在浏览器关闭发送请求
    elment-ui table组件 -- 远程筛选排序
    微信小程序 -- 数据请求
    2019年 学习计划
    vue 表单校验(二)
    ubuntu 学习
    vue-cli如何添加多种环境变量
    vue兼容ie
  • 原文地址:https://www.cnblogs.com/axiangcoding/p/10013327.html
Copyright © 2011-2022 走看看