Before reaching 50 reputation I am putting this declaimer in the first line of my answers:
I want to make a brief response in comment instead, but I don't have enough reputation so I am making a full answer, hopefully my ill-formed answers would still help.
DFS is perfect for this task -- That's basically what pre-order traversal is doing:
def DFS(node):
if(node == NULL) return
sequence += notNull(node.l)
sequence += notNull(node.r)
DFS(node.l)
DFS(node.r)
^^^ This is how your sequence is constructed.
Fortunately the inverse is quite straight forward:
def inverseDFS(node):
if(node == NULL) return
node.l = new Node() if(readBuffer(sequence) == '1') else NULL
node.r = new Node() if(readBuffer(sequence) == '1') else NULL
inverseDFS(node.l)
inverseDFS(node.r)
^^^ Only line 2 and 3 is modified, now instead of determining the next character of the sequence by the existance of child, we can determine the existance of child based on the next character read, as this is an iff relationship.
Here is a more sophisicated C++ code, and yes, I know my coding style may disgust some others.
/* Author haleyk10198 */
/* FOR ACM-ICPC WF*/
#include <bits/stdc++.h>
using namespace std;
struct Node{
static int nodeCnt;
int id;
Node *l, *r;
Node(){
l = r = nullptr;
this->id = nodeCnt++;
}
friend ostream& operator<<(ostream&, const Node);
}*root = new Node();
ostream& operator<<(ostream &out, const Node node){
cout << "Node id: " << node.id
<< " | left child is " << (node.l? node.l->id: -1)
<< " | right child is " << (node.r? node.r->id: -1) << endl;
}
int Node::nodeCnt, strStreamPos = 0;
string str;
void dfs(Node *node){
if(not node)
return;
if(str[strStreamPos++] == '1')
node->l = new Node();
if(str[strStreamPos++] == '1')
node->r = new Node();
cout << *node << endl;
dfs(node->l);
dfs(node->r);
}
int main(){
cin >> str;
dfs(root);
return 0;
}