二叉树基础

时间:2018-09-19 20:31:47

标签: java recursion tree binary recursive-datastructures

我正在执行leet代码任务,即Binary倾斜。问题的链接在这里:https://leetcode.com/problems/binary-tree-tilt/description/

我被困在这个问题上,所以看看解决方案,希望有人能为我解释以下解决方案的一部分:

    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. 左和右整数将设置为一个值。我不知道该值的来源,因为我认为需要使用root.val方法。你能用外行的术语解释吗?

  2. 当方法postOrder返回left + right + rootval时,该方法返回到哪里?递归方法如何使用它?

1 个答案:

答案 0 :(得分:0)

我认为让您感到困惑的是,将左右子树的总和与每个节点的倾斜度的计算方法合二为一。因此,我简化了您提供的代码,使其更易于理解,并添加了注释。但是,这种方法的效率要差得多,因为您需要计算每个节点的左和右子树的总和(在每次调用calculateTilt时),但它仍被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;    
    }
}

希望这会有所帮助!