563.b+树的坡度(javascript)563.BinaryTreeTilt

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

给你一个二叉树的根节点。 root ,计算并返回 整个树 的坡度 。

一个树的 节点的坡度 定义是该节点的左子树节点和右子树节点的总和。 差值的绝对值 如果没有左子树,则左子树的节点之和 0 ; 没有正确的子树也是如此。空节点的坡度为 0 。

整个树 的斜率是其所有节点的斜率之和。

Given the root of a binary tree, return the sum of every tree node’s tilt.

The tilt of a tree node is the absolute difference between the sum of all left subtree node values and all right subtree node values. If a node does not have a left child, then the sum of the left subtree node values is treated as 0. The rule is similar if the node does not have a right child.

示例 1:

输入:root = [1,2,3]
输出:1
解释:
节点 2 的坡度:|0-0| = 0(无子节点)
节点 3 的坡度:|0-0| = 0(无子节点)
节点 1 的坡度:|2-3| = 1(左子树是左子节点,因此也是。 2 ; 右子树是右子节点,因此和 3 )
坡度总和:0 + 0 + 1 = 1

示例 2:

输入:root = [4,2,9,3,5,null,7]
输出:15
解释:
节点 3 的坡度:|0-0| = 0(无子节点)
节点 5 的坡度:|0-0| = 0(无子节点)
节点 7 的坡度:|0-0| = 0(无子节点)
节点 2 的坡度:|3-5| = 2(左子树是左子节点,因此也是。 3 ; 右子树是右子节点,因此和 5 )
节点 9 的坡度:|0-7| = 7(没有左子树,所以和是。 0 ; 右子树正好是右子节点,因此和 7 )
节点 4 的坡度:|(3+5+2)-(9+7)| = |10-16| = 6(左子树值为 3、5 和 2 ,和是 10 ; 右子树值为 9 和 7 ,和是 16 )
坡度总和:0 + 0 + 0 + 2 + 7 + 6 = 15

示例 3:

输入:root = [21,7,14,1,1,2,2,3,3]
输出:9

提示:

  • 树中的节点范围在中。 [0, 104] 内
  • -1000 <= Node.val <= 1000

解题思路

var findTilt = function(root) {
    let sum=0
    var dfs=function(root){
        if(!root){
            return 0
        }
        let l=dfs(root.left)//获取左子树节点的总和。
        let r=dfs(root.right)//获取右子树的节点之和。
        sum+=Math.abs(l-r) //左子树节点和右子树节点的总和。 差值的绝对值 。
        return l+r+root.val  //return 一定有,否则l和r无法获取值
    }
    dfs(root)
    return sum
};

leetcode: https://leetcode-cn.com/problems/binary-tree-tilt/

版权声明

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