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

题目描述

563 Binary Tree Tilt https://leetcode-cn.com/problems/binary-tree-tilt/

Given a binary tree, return the tilt of the whole tree.

The tilt of a tree node is defined as the absolute difference between the sum of all left subtree node values and the sum of all right subtree node values. Null node has tilt 0.

The tilt of the whole tree is defined as the sum of all nodes' tilt.

Example:

Input:
         1
       /   \
      2     3
Output: 1
Explanation:
Tilt of node 2 : 0
Tilt of node 3 : 0
Tilt of node 1 : |2-3| = 1
Tilt of binary tree : 0 + 0 + 1 = 1

Note: The sum of node values in any subtree won't exceed the range of 32-bit integer. All the tilt values won't exceed the range of 32-bit integer.


解题过程

二叉树的坡度,递归计算二叉树节点和的过程中更新全局变量tilt即可。 时间复杂度 O(n),空间复杂度 O(n)

private static class SolutionV2020 {
    private int tilt;
    public int findTilt(TreeNode root) {
        tilt = 0;
        sum(root);
        return tilt;
    }

    // 计算树的所有结点值的和,过程中更新树的坡度
    private int sum(TreeNode root) {
        if (null == root) {
            return 0;
        }
        int left = sum(root.left);
        int right = sum(root.right);
        tilt += Math.abs(left - right);
        return left + right + root.val;
    }
}

GitHub代码

algorithms/leetcode/leetcode/_563_BinaryTreeTilt.java https://github.com/masikkk/algorithms/blob/master/leetcode/leetcode/_563_BinaryTreeTilt.java