1. 程式人生 > >563 Binary Tree Tilt

563 Binary Tree Tilt

div ger col left 時也 定義 class helper ndt

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 wont exceed the range of 32-bit integer. All the tilt values wont exceed the range of 32-bit integer.

這道題讓我們求二叉樹的坡度,某個結點的坡度的定義為該結點的左子樹之和與右子樹之和的差的絕對值,這道題讓我們求所有結點的坡度之和. 這道題最好的解法應該是用後序遍歷來做,因為後序遍歷的順序是左-右-根,那麽就會從葉結點開始處理,這樣我們就能很方便的計算結點的累加和,同時也可以很容易的根據子樹和來計算tilt,

public class Solution {
    int ans = 0;
    public int findTilt(TreeNode root) {	
        
        if (root == null) {
            return ans;
        }
        helper(root);
        return ans;
    }
    private int helper(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftSum = helper(root.left);
        int rightSum = helper(root.right);
        
        ans += Math.abs(leftSum - rightSum);
        return leftSum + rightSum + root.val;
    }
}

分治法原來就是後序遍歷, 遍歷到節點在處理, 然後返回到上層節點,

算法: 分治, 後序遍歷( 在設計求 結點的左子樹之和與右子樹之和的基礎上, 設計全局變量分治法求的差的絕對值)

容器: 全局變量, (要明白返回值是各個節點的子節點和, 而tilt 是總的, 都在變化, 只有子節點的可以當作返回值, 然後和是各個節點的tilt 和) 所以返回值的設定是子樹的和!!

563 Binary Tree Tilt