513.找树左下角的值(javascript)FindBottomLeftTreeValue

原创
小哥 3年前 (2022-11-10) 阅读数 2 #大杂烩

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

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

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

示例 1:

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

示例 2:

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

使用 height 记录穿越节点的高度,curVal 记录高度in curHeight 最左边节点的值。在深度优先搜索中,我们首先搜索当前节点的左子节点,然后搜索当前节点右子节点,再判断当前节点的高度。 height 是否大于 curHeight,如果是,那么将curVal 设置为当前节点的值,curHeight 设置为 height。

解题思路

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var findBottomLeftValue = function (root) {
    var DFS = function (root, height) {
        if (!root) {
            return
        }
        height++
        DFS(root.left, height)
        DFS(root.right, height)
        if (height > resultHeight) {
            resultVal = root.val
            resultHeight = height
        }
    }
    let resultHeight = 0
    let resultVal = null
    DFS(root, resultHeight)
    return resultVal
};

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

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除