LeetCode 563. 二叉树的坡度(Binary Tree Tilt) 38

563. 二叉树的坡度
563. Binary Tree Tilt

题目描述
给定一个二叉树,计算整个树的坡度。

一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是 0。

整个树的坡度就是其所有节点的坡度之和。

每日一算法2019/6/10Day 38LeetCode563. Binary Tree Tilt

示例:
输入:

     1
   /   
  2     3

输出: 1
解释:
结点的坡度 2 : 0
结点的坡度 3 : 0
结点的坡度 1 : |2-3| = 1
树的坡度 : 0 + 0 + 1 = 1

注意:

  1. 任何子树的结点的和不会超过 32 位整数的范围。
  2. 坡度的值不会超过 32 位整数的范围。

Java 实现
TreeNode Class

public class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    TreeNode(int x) {
        val = x;
    }
}
class Solution {
    public int findTilt(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int[] res = new int[1];
        postorder(root, res);
        return res[0];
    }

    public int postorder(TreeNode root, int[] res) {
        if (root == null) {
            return 0;
        }
        int leftSum = postorder(root.left, res);
        int rightSum = postorder(root.right, res);
        res[0] += Math.abs(leftSum - rightSum);
        return leftSum + rightSum + root.val;
    }
}

参考资料

原文地址:https://www.cnblogs.com/hgnulb/p/11000766.html