【问题标题】:How can I set positions to each node inside the Binary Search Tree?如何为二叉搜索树中的每个节点设置位置?
【发布时间】:2018-06-27 17:30:23
【问题描述】:

我想构建一个 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 方法的方法,以便将所有位置设置为节点。

【问题讨论】:

    标签: java binary-tree binary-search-tree inorder


    【解决方案1】:

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

    稍微简化一下

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多