Search code examples
javabinary-treebinary-search-treeinorder

How can I set positions to each node inside the Binary Search Tree?


I want to build a BST and set each of my nodes a position in ascending order. For example, if the binary search tree contains 3, 6, 2, 4, the positions of the node should be pos1-2, pos2-3, pos3-4, pos4- 6. Here is my insertBST method

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;
}

Here is the inOrderTraverseBST method that I want to set the positions to.

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;
}

But the inOrderTraversBST method is wrong. So I want to know how can I write the method for inOrderTraverseBST method in order to set all positions to the nodes.


Solution

  • Just remove the last line. With it you are re-assigning a node's position after its right subtree is traversed.

    Simplifying it a bit

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