在JavaScript中反序列化二进制搜索树

时间:2014-06-30 02:54:42

标签: javascript algorithm deserialization binary-search-tree

输入是具有空值的预订序列化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 个答案:

答案 0 :(得分:0)

所以我假设输入结构是节点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;
}