How to construct a binary tree using a level order traversal sequence

前端 未结 3 947
死守一世寂寞
死守一世寂寞 2020-12-31 23:56

How to construct a binary tree using a level order traversal sequence, for example from sequence {1,2,3,#,#,4,#,#,5}, we can construct a binary tree like this:



        
3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-01 00:34

    My approach is similar to Pham Trung yet intutive. We would maintain an array of Nodes of given data instead of using a queue. We would do reverse engineering on BFS using queue. because BFS for a tree is basically its Level Order Traversal (LOT).

    It is important to note that we should have the NULL childs of an node for the LOT to be unique and the reconstruction of Tree from LOT to be possible.

    In this case LOT : 1,2,3,-1,-1,4,-1,-1,5
    where I have used -1 instead of '#' to represent NULLs
    And Tree is

               1
            /    \
           2      3
          / \    /
        -1  -1  4
               / \
             -1   5
    

    Here, we can easily see that when 1 is popped from the BFS queue, it pushed its left child (2) and right child (3) in the queue. Similary, for 2 it pushed -1 (NULL) for both of its children. And the process is continued.
    So, we can follow the following pseudo code to generate the tree rooted at LOT[0]

    j = 1
    For every node in LOT:
      if n<=j: break
      if node  != NULL:
        make LOT[j] left child of node 
        if n<=j+1: break
        make LOT[j+1]  right child of node
      j <- j+2
    
    

    Finally, C++ code for the same
    Class Declaration and Preorder traversal

    class Node{
    public:
        int val;
        Node* lft, *rgt;
        Node(int x ):val(x) {lft=rgt=nullptr;}
    };
    
    
    void preorder(Node* root) {
        if(!root)   return;
        cout<val<<" ";
        preorder(root->lft);
        preorder(root->rgt);
    }
    

    Restoring Tree from LOT Logic

    
    int main(){
        int arr[] = {1,2,3,-1,-1,4,-1,-1,5};
        int n = sizeof(arr)/sizeof(int);
        Node* brr[n];
        for(int i=0;ilft = brr[j++];
            if(jrgt = brr[j++];
        }
        preorder(brr[0]);
    }
        
    

    Output: 1 2 3 4 5

提交回复
热议问题