# 21-05-25-找树左下角的值

# 题目地址

https://leetcode-cn.com/problems/find-bottom-left-tree-value/

# 题目描述

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

示例 1:

输入:

    2
   / \
  1   3

输出:
1
 

示例 2:

输入:

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

输出:
7

# 前置知识

广度优先遍历

二叉树的遍历

# 思路

二叉树的广度优先遍历,然后在每层的第一个节点处做结果值result的更新,判断是否是第一个节点的更新用一个flag值作判断。整体比较简单,关键还是要熟悉二叉树的广度优先遍历写法。

# 代码

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var findBottomLeftValue = function(root) {
  const queue = [root];
  let result = root.val;
  while (queue.length > 0) {
    let length = queue.length;
    let flag = false;
    // 当前层级
    while (length --) {
      let node = queue.shift();
      if (node) {
        if (!flag) { // 每一层只在第一个节点的时候改一次
          result = node.val;
          flag = true;
        }
        queue.push(node.left);
        queue.push(node.right);
      }
    }    
  }
  return result;
};

# 复杂度分析

  • 时间复杂度:O(N)
  • 空间复杂度:O(N)
Last Updated: 7/8/2021, 2:12:40 AM