-4

I am following a leet code task which is called Binary tilt. The link to the question is here: https://leetcode.com/problems/binary-tree-tilt/description/

I was stuck on the question so had a look at the solution and I was hoping someone could interpret parts of the below solution for me:

    public class Solution {
      int result = 0;

      public int findTilt(TreeNode root) {
        postOrder(root);
        return result;
      }

      private int postOrder(TreeNode root) {
        if (root == null) return 0;

        int left = postOrder(root.left);
        int right = postOrder(root.right);

        result += Math.abs(left - right);

        return left + right + root.val;
      }
  }
  1. integers left and right are set to a value every time the recursion happens. What I don’t understand is where this value comes from as in I thought the root.val method would need to be used. Can you explain this in layman terms?

  2. When the method postOrder returns left+right+rootval where is the method returned to? How is it used with the recursive method?

LuCio
  • 4,285
  • 1
  • 15
  • 29

1 Answers1

0

I think what is confusing you is that calculating sum of left and right subtree and calculating tilt for each node is combined in one method. So, I simplified the code that you provided for it to be easier to understand and added comments to it. Though, this way it is much less effective cause you calculate sum for left and right subtree of every node(on each call to calculateTilt), but it is still accepted by leetcode:

public class Solution {
    int result = 0; //instance variable to accumulate result(tilt) for all nodes in the tree

    public int findTilt(TreeNode root) {
        calculateTilt(root);
        return result;
    }

    private void calculateTilt(TreeNode root) {
        if (root == null) 
            return;

        int left = findTreeSum(root.left); //find sum of all nodes values of the left subtree
        int right = findTreeSum(root.right); //find sum of all nodes values of the right subtree

        result += Math.abs(left - right); //add tilt of current node to the result

        calculateTilt(root.left); //recursively calculate tilt for the left subtree
        calculateTilt(root.right); //recursively calculate tilt for the right subtree
    }

    //method to find sum of all nodes values for the tree starting at root
    private int findTreeSum(TreeNode root){
        if (root == null) 
            return 0;

        return findTreeSum(root.left) + findTreeSum(root.right) + root.val;    
    }
}

Hope this will help!

Sergei Sirik
  • 1,184
  • 1
  • 9
  • 26