首页 > 其他分享 >leetcode 513. Find Bottom Left Tree Value 找树左下角的值 (简单)

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

时间:2022-09-30 19:12:44浏览次数:83  
标签:node Bottom int 找树 二叉树 res 左下角 maxDpeth 节点

一、题目大意

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

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

示例 1:

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

输出: 1

示例 2:

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

输出: 7

提示:

  • 二叉树的节点个数的范围是 [1,104]

  • -231 <= Node.val <= 231 - 1

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/find-bottom-left-tree-value
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

二、解题思路

求二叉树的最左下树节点的值,也就是最后一行左数第一个值,可以用先序遍历来做,维护一个最大尝试和该尝试的节点值,由于先序遍历遍历的顺序是根左右,所以每一行最左边的节点肯定最先先遍历到,由于是新一行,那么当前尝试肯定比之前的最大深度大,所以可以更新最大深度为当前深度,节点值res为当前节点值,这样在遍历到该行其他节点时就不会更新res了

三、解题方法

3.1 Java实现

public class Solution {
    public int findBottomLeftValue(TreeNode root) {
        int maxDepth = 1;
        int[] res = new int[]{root.val};
        helper(root, 1, maxDepth, res);
        return res[0];
    }

    void helper(TreeNode node, int depth, int maxDpeth, int[] res) {
        if (node == null) {
            return;
        }
        if (depth > maxDpeth) {
            maxDpeth = depth;
            res[0] = node.val;
        }
        helper(node.left, depth + 1, maxDpeth, res);
        helper(node.right, depth + 1, maxDpeth, res);
    }
}

四、总结小记

  • 2022/9/30 今天有点着急

标签:node,Bottom,int,找树,二叉树,res,左下角,maxDpeth,节点
From: https://www.cnblogs.com/okokabcd/p/16745872.html

相关文章

  • 多路查找树
    二叉树存在的问题二叉树需要加载到内存的,如果二叉树的节点少,没有什么问题,但是如果二叉树的节点很多(比如1亿)问题1:在构建二叉树时,需要多次进行i/o操作(海量数据存在数......
  • 【力扣算法题】寻找树中最左下结点的值
    题目:给定一个二叉树的根节点root,请找出该二叉树的 最底层 最左边 节点的值。假设二叉树中至少有一个节点。样例示例1:输入:root=[2,1,3]输出:1示例2:  ......
  • BottomSheetDialog 找不到符号design_bottom_sheet
    BottomSheetDialog使用BottomSheetDialogbottomSheetDialog=newBottomSheetDialog(mContext);bottomSheetDialog.setContentView(R.layout.layout_bottom_p......
  • 单词查找树
    本节内容:学习两种字符串查找相关的数据结构应用:基于字符串键的符号表算法:基于字符串键的查找算法数据结构:单词查找树(R向单词查找树)三向单词查找树(TST)性能:查找命......