How to construct a binary tree using a level order traversal sequence
Assume using array int[]data
with 0-based index, we have a simple function to get children:
Left child
int getLeftChild(int index){ if(index*2 + 1 >= data.length) return -1;// -1 Means out of bound return data[(index*2) + 1]; }
Right child
int getRightChild(int index){ if(index*2 + 2 >= data.length) return -1;// -1 Means out of bound return data[(index*2) + 2]; }
Edit: Ok, so by maintaining a queue, we can build this binary tree.
We use a queue to maintain those nodes that are not yet processed.
Using a variable count to keep track of the number of children added for the current node.
First, create a root node, assign it as the current node. So starting from index 1 (index 0 is the root), as the count is 0, we add this node as left child of the current node. Increase count. If this node is not '#', add it to the queue.
Moving to the next index, the count is 1, so we add this as right child of current node, reset count to 0 and update current node (by assigning the current node as the first element in the queue). If this node is not '#', add it to the queue.
int count = 0;
Queue q = new Queue();
q.add(new Node(data[0]);
Node cur = null;
for(int i = 1; i < data.length; i++){
Node node = new Node(data[i]);
if(count == 0){
cur = q.dequeue();
}
if(count==0){
count++;
cur.leftChild = node;
}else {
count = 0;
cur.rightChild = node;
}
if(data[i] != '#'){
q.enqueue(node);
}
}
class Node{
int data;
Node leftChild, rightChild;
}