Java Solution, no globle varible, Easy and clean


  • 2
    E

    I don't understand the question when I do it at the first time.
    But now I got it.
    For example:
        1
       /   \
      2     3
     / \    /
    4  # 5

    Output: 11
    Explanation:
    Tilt of node 4 : 0
    Tilt of node 5 : 0
    Tilt of node 2 : |4-0| = 4
    Tilt of node 3 : |5-0| = 5
    Tilt of node 1 : |sum(2,4)-sum(3,5)| = |6-8| = 2
    Tilt of binary tree : 0 + 0 + 4 + 5 + 2 = 11

        public int findTilt(TreeNode root) {
            if (root == null) return 0;
            int curVal = 0;
            curVal = Math.abs(sumSubTree(root.left) - sumSubTree(root.right));
            return curVal + findTilt(root.left) + findTilt(root.right);
        }
    
        private int sumSubTree(TreeNode root) {
            if (root == null) return 0;
            return root.val + sumSubTree(root.left) + sumSubTree(root.right);
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.