2

I try to create a BST with the following code, nums = [4,5,8,2]

var TreeNode = function (val) {
    this.val = val;
    this.left = this.right = null;
    this.count = 1;
}

var constructBST = function(nums) {
    if (nums.length === 0) return null;
    let root = new TreeNode(nums[0]);
    for (let i = 1; i < nums.length; i++) {
        let currentNode = root;
        while (currentNode) {
             if (currentNode.val > nums[i]) {
                currentNode = currentNode.left;
            } else if (currentNode.val < nums[i]) {
                currentNode = currentNode.right;
            }
        }
        currentNode = new TreeNode(nums[i]);
    }
    console.log(root);
    return root;
}

I take root as current node for each iteration, and move the currentNode based on the value, but when I print out the root after I iterate the array, why my root node doesn't change?

This is the output:

TreeNode { val: 4, right: null, left: null, count: 1 }、

Edit: say if I have a root node 3, and it has no child, when I set current node to root, and if I move currentNode = currentNode.left; Doesn't this mean there is a connection between currentNode and the root? I thought the currentNode would now represent root's left child. If I make any changes to currentNode, the root's left child would also change

1
  • The problem seems to be that while you navigate correctly in the tree, the newly created nodes are not actually connected to the tree. Commented Jun 14, 2018 at 5:13

1 Answer 1

2

You seem to be navigating the tree correctly, but the newly created nodes are never connected to their intended parent. Change the function as follows.

var constructBST = function(nums) {
    if (nums.length === 0) return null;
    let root = new TreeNode(nums[0]);
    for (let i = 1; i < nums.length; i++) {
        let currentNode = root;
        while (currentNode) {
             if (currentNode.val > nums[i]) {
                if (null == currentNode.left) {
                    currentNode.left = new TreeNode(nums[i]);
                    currentNode = null;
                } else {
                    currentNode = currentNode.left;
                }
            } else if (currentNode.val < nums[i]) {
                if (null == currentNode.right) {
                    currentNode.right = new TreeNode(nums[i]);
                    currentNode = null;
                } else {
                    currentNode = currentNode.right;
                }
            }
        }
    }
    console.log(root);
    return root;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.