Easy to understand Java solution


  • 0
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int findTilt(TreeNode root) {
            if(root == null) return 0;
            else {
                int tilt = Math.abs(sumLeft(root.left) - sumRight(root.right));
                return tilt + findTilt(root.left) + findTilt(root.right);
            }
        }
        
        private int sumLeft(TreeNode root) {
            if(root == null) return 0;
            else {
                return root.val + sumLeft(root.left) + sumLeft(root.right);
            }
        }
        
        private int sumRight(TreeNode root) {
            if(root == null) return 0;
            else {
                return root.val + sumRight(root.left) + sumRight(root.right);
            }
        }
    }
    

Log in to reply
 

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