Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 二叉树最大路径和中的递归调用解释_Algorithm_Recursion_Tree - Fatal编程技术网

Algorithm 二叉树最大路径和中的递归调用解释

Algorithm 二叉树最大路径和中的递归调用解释,algorithm,recursion,tree,Algorithm,Recursion,Tree,这就是问题所在: 给定一棵二叉树,求最大路径和 对于这个问题,路径被定义为来自某个节点的任意节点序列 起始节点到树中沿父子节点的任意节点 连接。路径必须至少包含一个节点,并且不需要 通过根 例如:给定下面的二叉树 1 / \ 2 3 返回6 此问题的递归解决方案如下所示: int max = Integer.MIN_VALUE; public int maxPathSum(TreeNode root) { helper(root); return max; }

这就是问题所在:

给定一棵二叉树,求最大路径和

对于这个问题,路径被定义为来自某个节点的任意节点序列 起始节点到树中沿父子节点的任意节点 连接。路径必须至少包含一个节点,并且不需要 通过根

例如:给定下面的二叉树

   1
  / \
 2   3
返回6

此问题的递归解决方案如下所示:

int max = Integer.MIN_VALUE;

public int maxPathSum(TreeNode root) {
    helper(root);
    return max;
}

private int helper(TreeNode root) {
    if (root == null) return 0;
    int left = Math.max(helper(root.left), 0);
    int right = Math.max(helper(root.right), 0);
    max = Math.max(max, root.val + left + right);
    return root.val + Math.max(left, right);
}
我们为left child调用
helper
,并检查left child是否大于零

然后我们为右子对象调用
helper
,并检查右子对象是否大于零

然后我们用sum
root.val+left+right
检查当前
max
值-这也很清楚

但是,在返回语句中,我们只有根值和一个子值之和。
为什么我们在这里只取一个子项,而不取两个子项,如果它们都为正呢?

递归方法不返回解本身,它只返回该部分的最大值。最终解决方案在max变量中计算

如果检查maxPathSum方法,它将返回最大值,而不是从helper方法返回的值

这是因为解决方案可能不触及根,如下所示:

       0
     /   \
    1     0
   / \   / \
  2   3 0   0

在helper方法中有一个赋值
max=Math.max(max,root.val+left+right)-这很清楚。但是为什么我们返回
root.val+Math.max(左、右)?求和
root.val
的目的是什么,这如何影响
max
变量的值?helper方法返回给定子树的max-non-complete-path。max变量包含“finished”路径,即在给定子树中开始和结束的路径。因此,当helper方法返回时,它返回一个可能的半路径,可以与从另一个分支开始的另一半组合,如果这两个一半的组合值大于实际最大值,那么它将是新的最大值。