当前位置:网站首页>The sword refers to OfferⅡ 045. The bottommost leftmost value of the binary tree dfs

The sword refers to OfferⅡ 045. The bottommost leftmost value of the binary tree dfs

2022-08-10 16:48:00 HotRabbit.

题目

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

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

示例 1:

img

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

示例 2:

img

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

提示:

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

注意:本题与主站 513 题相同: https://leetcode-cn.com/problems/find-bottom-left-tree-value/

Related Topics

  • 深度优先搜索
  • 广度优先搜索
  • 二叉树

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

思路

定义两个全局变量,Record the height and the current value that matches the meaning of the question,深度遍历,When traversing a node above the current height,记录当前值,先dfs左节点,再dfs右节点,This way if the left node has a value,The right node is not as tall as the left node,won't get.

题解

class Solution {
    
    int curVal = 0;
    int curHeight = 0;

    public int findBottomLeftValue(TreeNode root) {
    
        int curHeight = 0;
        dfs(root,0);
        return curVal;
    }

    public void dfs(TreeNode root, int height){
    
        if (root == null) return;
        height++;
        dfs(root.left,height);
        dfs(root.right,height);
        if (height > curHeight){
    
            curHeight = height;
            curVal = root.val;
        }
    }
}
原网站

版权声明
本文为[HotRabbit.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/222/202208101611518287.html