【陪伴式刷题】Day 16|二叉树|513.找树左下角的值(Find Bottom Left Tree Value)

274 阅读2分钟

刷题顺序按照代码随想录建议

题目描述

英文版描述

Given the root of a binary tree, return the leftmost value in the last row of the tree.

Example 1:

Input: root = [2,1,3] Output: 1

Example 2:

Input: root = [1,2,3,4,null,5,6,null,null,7] Output: 7

Constraints:

  • The number of nodes in the tree is in the range [1, 10^4].
  • -2^31 <= Node.val <= 2^31 - 1

英文版地址

leetcode.com/problems/fi…

中文版描述

给定一个二叉树的 根节点 root,请找出该二叉树的 最底层 最左边 节点的值。

假设二叉树中至少有一个节点。

示例 1:

输入: root = [2,1,3] 输出: 1

示例 2:

输入: [1,2,3,4,null,5,6,null,null,7] 输出: 7

提示:

  • 二叉树的节点个数的范围是 [1,10^4]
  • -2^31 <= Node.val <= 2^31 - 1

中文版地址

leetcode.cn/problems/fi…

解题方法

递归法

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    int result = 0;
    int depthMax = 0;
    public int findBottomLeftValue(TreeNode root) {
        int depth = 1;
        recursion(root, depth);
        return result;
    }

    private void recursion(TreeNode root, int depth) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            if (depthMax < depth) {
                depthMax = depth;
                result = root.val;
            }
            return;
        }
        if (root.left != null) {
            recursion(root.left, depth + 1);
        }
        if (root.right != null) {
            recursion(root.right, depth + 1);
        }
    }
}

复杂度分析

  • 时间复杂度:O(n),其中 n 是二叉树的节点数,每一个节点至少被遍历一次
  • 空间复杂度:O(n),为递归过程中栈的开销

迭代法

class Solution {
    public int findBottomLeftValue(TreeNode root) {
        int result = 0;
        Deque<TreeNode> deque = new LinkedList<>();
        deque.addLast(root);
        while (!deque.isEmpty()) {
            TreeNode treeNode = deque.pollFirst();
            if (treeNode.right != null) {
                deque.addLast(treeNode.right);
            }
            if (treeNode.left != null) {
                deque.addLast(treeNode.left);
            }
            result = treeNode.val;
        }
        return result;
    }
}

创建一个双端队列来保存要遍历的节点,将根节点添加到队列尾部,进入while循环♻️,继续循环的条件为当队列不为空,在while循环内,移除队列头部的节点,并取出值放到结果中,判断该节点右孩子是否为空,如果非空则将其添加到队列尾部,继续判断该节点左孩子是否为空,如果非空则将其添加到队列尾部,最后将当前节点的值赋给结果变量result,这样在遍历结束后,结果中保存的值就是最下层最后进入队列的节点,即最左边的节点值。这种方式,总会先遍历右子树,这就保证了在同一层中,左边的节点后于右边的节点被遍历。所以,最后一次更新结果的节点,既一定是所求的最底层的,又一定是最左边的节点。

复杂度分析

  • 时间复杂度:O(n),其中 n 是二叉树的节点数,每一个节点恰好被遍历一次
  • 空间复杂度:O(n),在满二叉树的情况下,叶子节点的数量约为 n/2,所以最坏情况下空间复杂度为O(n)