513-Find-Bottom-Left-Tree-Value

34次阅读

共计 748 个字符,预计需要花费 2 分钟才能阅读完成。

题目要求

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

Note: You may assume the tree (i.e., the given root node) is not NULL.
现有一棵二叉树,要求找到树中最后一行最左边的节点的值。

思路和代码

这题其实就是考察树的遍历。那么如何遍历树能够找到最后一行最左边的值呢?首先一个就是水平遍历,逐个遍历树的每一行,每次都记录该行最左边的值。当没有下一行时,则返回当前记录的行的最左边的值。

还有一种方法就是通过后序遍历。每次遍历时将当前节点所在的深度传递过去,并且和已知的最远行数进行比较。如果深度大于当前的行数,则说明该值是最远处的最左边的值。

代码如下:

    int depth = 0;
    int value = 0;
    public int findBottomLeftValue(TreeNode root) {findBottomLeftValue(root, 1);
        return value;
    }

    public void findBottomLeftValue(TreeNode root, int depth) {if (root == null) return;
        if (root.left == null && root.right == null && depth > this.depth) {
            value = root.val;
            this.depth = depth;
            return;
        }
        findBottomLeftValue(root.left, depth+1);
        findBottomLeftValue(root.right, depth+1);
    }

正文完
 0