Java Postorder Traversal(easy to understand)


  • 1
    F
    public class Solution {
    
      public int findTilt(TreeNode root) {
        if (root == null) return 0;
        return Math.abs(sum(root.left, 0) - sum(root.right, 0)) + findTilt(root.left) + findTilt(root.right);
      }
    
      private int sum(TreeNode root, int sum) {
      	if (root == null) return sum;
      	return sum(root.left, sum) + sum(root.right, sum) + root.val;
      }
    }
    

  • 0
    U

    You dont need to add extra parameter for sum. You can do this.

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

Log in to reply
 

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