Java postorder solution


  • 0
    K
    public class Solution {
        int tilt = 0;
        public int findTilt(TreeNode root) {
            find(root);
            return tilt;
        }
        // While computing the tilt at every node, return the sum to its parent node for computing tilt's recursively.
        private int find(TreeNode root) {
            if(root == null) return 0; // Base case
            int lsum = 0, rsum = 0;
            if(root.left != null){
                lsum = find(root.left);
            }
            if(root.right != null){
                rsum = find(root.right);
            }
            tilt += Math.abs(lsum - rsum); // Compute tilt for the current node
            return root.val+lsum+rsum; // return the sum until current node
        }
    }
    

Log in to reply
 

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