LeetCode 513. Find Bottom Left Tree Value

LeetCode 513. Find Bottom Left Tree Value (找树左下角的值)

题目

链接

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

问题描述

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

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

示例

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

提示

二叉树的节点个数的范围是 [1,104]
-231 <= Node.val <= 231 - 1

思路

需要借助树深度来计算,当左子树更深或一样深时找左子树,不然找右子树。

复杂度分析

时间复杂度 O(n2)
空间复杂度 O(1)

代码

Java

    public int findBottomLeftValue(TreeNode root) {
        if(root.left==null&&root.right==null){
            return root.val;
        }
        if(getDepth(root.left)>=getDepth(root.right)){
            return findBottomLeftValue(root.left);
        }else {
            return findBottomLeftValue(root.right);
        }
    }

    public int getDepth(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            return 1 + Math.max(getDepth(root.left), getDepth(root.right));
        }
    }
posted @ 2022-06-03 11:18  cheng102e  阅读(15)  评论(0编辑  收藏  举报