Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.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_Binary Tree_Binary Search Tree_Inorder - Fatal编程技术网

Java 如何设置二进制搜索树中每个节点的位置?

Java 如何设置二进制搜索树中每个节点的位置?,java,binary-tree,binary-search-tree,inorder,Java,Binary Tree,Binary Search Tree,Inorder,我想构建一个BST,并按升序将每个节点设置为一个位置。例如,如果二叉搜索树包含3、6、2、4,则节点的位置应为pos1-2、pos2-3、pos3-4、pos4-6。 这是我的insertBST方法 TreeNode insertBST(TreeNode parent, int value) { if (parent == null) { parent = new TreeNode(value); return parent; } if (

我想构建一个BST,并按升序将每个节点设置为一个位置。例如,如果二叉搜索树包含3、6、2、4,则节点的位置应为pos1-2、pos2-3、pos3-4、pos4-6。 这是我的insertBST方法

TreeNode insertBST(TreeNode parent, int value) {
    if (parent == null) {
        parent = new TreeNode(value);
        return parent;
    }
    if (value <= parent.value) {
        parent.leftChild = this.insertBST(parent.leftChild, value);
    } else if (value >= this.root.value) {
        parent.rightChild = this.insertBST(this.root.rightChild, value);
    }

    return parent;
}

但是inOrderTraversBST方法是错误的。因此,我想知道如何为inOrderTraverseBST方法编写方法,以便为节点设置所有位置。

只需删除最后一行即可。使用它,您可以在遍历节点的右子树后重新指定节点的位置

简化一点

public void inOrderTraverseBST(TreeNode root) {
    if (root == null) {
        return;
    }
    this.inOrderTraverseBST(root.leftChild);
    root.position = this.count++;
    this.inOrderTraverseBST(root.rightChild);
}
public void inOrderTraverseBST(TreeNode root) {
    if (root == null) {
        return;
    }
    this.inOrderTraverseBST(root.leftChild);
    root.position = this.count++;
    this.inOrderTraverseBST(root.rightChild);
}