[英]Deserialize Binary Search Tree in JavaScript
输入是具有空值的预序列化BST。 这些值已读入具有整数和空值的数组。
样本输入
[ 6, 3, null, null, 8, null, 9, null, null ]
想要的输出
{ _root:
{ value: 6,
left: { value: 3,
left: null,
right: null },
right: { value: 8,
left: null,
right: { value: 9,
left: null,
right: null } } } }
这是BST的基本界面:
function BinarySearchTree() {
this._root = null;
}
BinarySearchTree.prototype = {
//restore constructor
constructor: BinarySearchTree,
insert: function(value) {
//create a new item object, place data in
var node = {
value: value,
left: null,
right: null
},
current;
// more code (works, but omitted for this question)
}
};
我们如何反序列化上面的输入,以便最终得到BinarySearchTree? 这是沿着这些路线的递归预订遍历吗?
function deserialize(arr) {
var result = new BinarySearchTree();
result._root = arr[0];
if (arr[1] === null) {
result._root.left = null;
}
if () {
return null;
}
node.left = deserialize(arr);
node.right = deserialize(arr);
return result;
}
因此,我假设输入结构将是节点1,左子节点1,左孙子节点1,...右子节点1,右孙子节点1,...
我们可以维护一个堆栈来构建树,这有助于轻松检索更高级别的树(或者我们可以向每个节点的父级添加指针)。
Java代码:
void builTree(Integer input){
Node root = new Node(input[0]);
Node cur = root;
for(int i = 1; i < input.length; i++){
if(cur.count <=1){
cur = update(cur,input[i]);
}else{
while(cur.count == 2){//This while loop may not necessary
cur = cur.parent;
}
cur = update(cur, s, input[i]);
}
}
}
Node update(Node node, Integer input){
if(node.count == 0){
node.left = new Node(input);
node.left.parent = node;
node.count++;
if(input != null){
return node.left;
}
}else if(node.count == 1){
node.right = new Node(input);
node.right.parent = node;
node.count++;
if(input != null){
return node.right;
}
}
return node;
}
class Node{
int value , count;//variable count will tell whether a node is full or not
Node left, right, parent;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.