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.

Divide and Conquer

Time Complexity
O(N)
Space Complexity
O(logn)

思路

这题给的example实在很confusing...举个栗子,这样的树返回的结果是11,所以我们要keep一个全局的result,一有结果就加,同时还要记录left subtree的sum 和right subtree的sum

     1
   /   \
  2     3
 /     /
 4     5

代码

public int findTilt(TreeNode root) {
    if(root == null) return 0;
    int[] res = new int[]{0};
    helper(root, res);
    return res[0];
}

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

annielulu
5 声望5 粉丝