首页 > 解决方案 > 如何为二叉搜索树中的每个节点设置位置?

问题描述

我想建立一个 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;
}

这是我要设置位置的 inOrderTraverseBST 方法。

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

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

标签: javabinary-treebinary-search-treeinorder

解决方案


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

稍微简化一下

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

推荐阅读