Recursive Java Solution - No Extra Storage


  • 0
    T
    public class Solution {
        public int findTilt(TreeNode root) {
            if (root == null) {
                return 0;
            }
            int l = sum(root.left);
            int r = sum(root.right);
            return Math.abs(l - r) + findTilt(root.left) + findTilt(root.right);
        }
        
        public int sum(TreeNode n) {
            if (n == null) {
                return 0;
            } else {
                return sum(n.left) + sum (n.right) + n.val;
            }
        }
    }
    

Log in to reply
 

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