我尝试使用以下代码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;
}
我将root作为每个迭代的当前节点,并根据值移动currentNode,但是当我在迭代数组后打印出root时,为什么我的根节点不会改变?
这是输出:
TreeNode { val: 4, right: null, left: null, count: 1 }、
编辑:如果我有一个根节点3,并且它没有子节点,当我将当前节点设置为root时,如果我移动currentNode = currentNode.left; 这是不是意味着currentNode与root之间存在连接?我认为currentNode现在代表root的左子。如果我对currentNode进行任何更改,则root的左子项也会更改
答案 0 :(得分:2)
您似乎正在正确地导航树,但新创建的节点永远不会连接到其预期的父节点。更改功能如下。
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;
}