【问题标题】:Binary Tree basics二叉树基础
【发布时间】:2018-09-19 20:31:46
【问题描述】:

我正在关注一个名为 Binarytilt 的 leet 代码任务。问题的链接在这里: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时,方法返回到哪里?与递归方法如何配合使用?

【问题讨论】:

  • 调试它,或者更好地理解绘制递归调用堆栈。

标签: java recursion tree binary recursive-datastructures


【解决方案1】:

我认为让您感到困惑的是,计算左右子树的总和和计算每个节点的倾斜度是结合在一种方法中的。因此,我简化了您提供的代码,使其更易于理解,并向其中添加了 cmets。虽然,这种方式效率低得多,因为您计算每个节点的左右子树的总和(在每次调用 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;    
    }
}

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-14
    • 2021-01-13
    • 2012-01-09
    相关资源
    最近更新 更多