Java recursive solution


  • 0
    J

    Java recursive solution

    /**
     * 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;
            
            int rootTilt = Math.abs(sumTree(root.left) - sumTree(root.right));
            return findTilt(root.left) + findTilt(root.right) + rootTilt;
        }
        
        public int sumTree(TreeNode root){
            if(root == null) return 0;
            return root.val + sumTree(root.left) + sumTree(root.right);
        }
    }

Log in to reply
 

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