Wednesday, September 14, 2016

serialize deserialize binary tree

//examples
   4
 2   6
1 3 5 7

4 2 1 - - 3 - - 6 5 - - 7 - -

 1
2 3
 - 4
  - 5

1 2 - - 3 - 4 - 5 - - 
Serialize using pre-order traversal and recording nulls.
serialize(n):
    buffer = new buffer()
    (n, buffer)
    return buffer
(n, buffer):
    buffer.append(n == null ? "-" : n.value)
    if n == null:
        return
    (n.left, buffer)
    (n.right, buffer)
deserialize(a):
    return (a, {value = 0})
(a, i):
    if i.value >= a.length():
        return null
    x = a[i.value]
    i.value++
    if x == -1: //or null
        return null
    n = new node(x)
    n.left  = (a, i)
    n.right = (a, i)
    return n
[Hat tip to MP]

No comments:

Post a Comment