Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.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
Java 它如何确保一个节点是祖先而不是兄弟节点?_Java_Algorithm_Tree_Binary Tree - Fatal编程技术网

Java 它如何确保一个节点是祖先而不是兄弟节点?

Java 它如何确保一个节点是祖先而不是兄弟节点?,java,algorithm,tree,binary-tree,Java,Algorithm,Tree,Binary Tree,我试图解决: 给定二叉树的根,找出存在不同节点a和B的最大值V,其中V=| a.val-B.val |,a是B的祖先。(如果a的任何子节点等于B,或者a的任何子节点都是B的祖先,则a节点a是B的祖先。) 其中一项建议如下: public int maxAncestorDiff(TreeNode root){ 返回dfs(root,root.val,root.val); } 公共int dfs(树节点根、int mn、int mx){ if(root==null)返回mx-mn; mx=Math.

我试图解决:

给定二叉树的根,找出存在不同节点a和B的最大值V,其中V=| a.val-B.val |,a是B的祖先。(如果a的任何子节点等于B,或者a的任何子节点都是B的祖先,则a节点a是B的祖先。)

其中一项建议如下:

public int maxAncestorDiff(TreeNode root){
返回dfs(root,root.val,root.val);
}
公共int dfs(树节点根、int mn、int mx){
if(root==null)返回mx-mn;
mx=Math.max(mx,root.val);
mn=Math.min(mn,root.val);
返回Math.max(dfs(root.left,mn,mx),dfs(root.right,mn,mx));
}

这基本上只是对树的一个前序遍历。我无法理解它如何确保node
A
是node
B
的祖先(而不是兄弟姐妹)?

我们来分析一下

你是对的,这只是一个预阶横截。重要的是,对于每个节点,我们都有一个最小值和一个最大值。当我们沿着树向下迭代时,这些值分别变小和变大。在任何一个给定节点上,我们只使用该节点的值更新
mn
mx
。因此,当我们将
mn
mx
传递给子节点时,这些值仅反映树中直到当前节点的节点

或许这些评论可以更好地说明这一点:

public int dfs(TreeNode root, int mn, int mx) {

    // this is the base case, at some point mn was encountered and mx was encountered
    // on the path to this node, this is the maximum possible difference along that path
    if (root == null) return mx - mn;

    // on our current path through the tree, update the max / min value we have encountered
    mx = Math.max(mx, root.val);
    mn = Math.min(mn, root.val);

    // the mn and mx at this point are only reflective of this node and it's ancestors
    // integers are immutable so a function call down the line won't change the 
    // mx and mn here, but rather create a new mx and mn at that node
    // we pass the updated mx and mn to the node's children, exploring paths
    // down the tree

    return Math.max(dfs(root.left, mn, mx), dfs(root.right, mn, mx));
}

在包含的递归树遍历算法中,不可能访问节点的同级。请注意,该算法返回左树和右树结果的最大值。因此,可以说,左树和右树永远无法“交互”。@Arch2K,请您详细说明您的第一句话——“无法访问节点的兄弟节点”?显示的算法更新当前节点的最大值和最小值,然后使用更新后的max和min值递归调用左子树和右子树上的函数。在获得右子树和左子树的返回值后,它将返回这两个子树中的最大值。在这种情况下,对于dfs的每次调用,所讨论的节点只更新max和min值及其左、右子树。这里没有编写这样的代码,即节点能够访问其同级节点。