【发布时间】:2016-08-18 01:34:24
【问题描述】:
我正在尝试编写将 BST 转换为双向链表的算法。这就是我到目前为止所拥有的。下面是代码:
function TreeNode(val) {
this.val = val;
this.left = this.right = null;
}
function BinaryTree() {
this.root = null;
}
BinaryTree.prototype.push = function(val) {
var root = this.root;
if(!root) {
this.root = new TreeNode(val);
return;
}
var currentNode = root;
var newNode = new TreeNode(val);
while(currentNode) {
if (val < currentNode.val) {
if(!currentNode.left) {
currentNode.left = newNode;
break;
} else {
currentNode = currentNode.left;
}
} else if(val > currentNode.val) {
if(!currentNode.right) {
currentNode.right = newNode;
break;
} else {
currentNode = currentNode.right;
}
}
}
}
var bt = new BinaryTree();
bt.push(4);
bt.push(2);
bt.push(5);
bt.push(1);
bt.push(3);
//console.log(bt);
//var node = bt.root;
function Node(node) {
//this.data = value;
//this.previous = this.next = null;
var head = null;
var tail = null;
var prev = null;
console.log(bstToLL(node, head, prev, tail));
}
//function DoublyLinkedList() {
// this.head = null;
// this.prev = null;
// this.tail = null;
//}
function bstToLL(node, head, prev, tail) {
if (node === null) {
return;
}
bstToLL(node.left, head, prev, tail);
if (head === null) {
head = node;
//console.log(head)
}
if (prev === null) {
prev = node;
//console.log(prev)
} else {
//console.log(node);
//console.log(prev);
node.left = prev;
prev.right = node;
}
prev = node
bstToLL(node.right, head, prev, tail);
if(node.right === null) {
tail = node;
}
return head;
}
Node(bt.root);
代码有效,但我认为它没有得到正确的结果。二叉树看起来像-
4
/ \
2 5
/ \
1 3
当我从 bstToLL() 方法返回头部时,我得到一个 val 4 指向右孩子 5 和左孩子 2 的对象,依此类推。
如果您运行代码并检查调试器,您将看到头对象。
如果我以正确的方式执行此操作,有人可以指导我吗?如何解决结果?
【问题讨论】:
-
请在问题本身中包含所有相关代码。不保证该链接将来仍然有效
标签: javascript algorithm linked-list binary-search-tree