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

前端 未结 3 1060
死守一世寂寞
死守一世寂寞 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:28

    we can build this binary tree from level order traversal by maintaining a queue. Queue is used to maintain those nodes that are not yet processed.

    1. Using a variable count(index variable) to keep track of the number of children added for the current node.

    2. First, create a root node, assign it as the current node. So starting from index 1, index value is 1 means, we will add the next value as left node. index value is 2 means we will add the next value as right node and index value 2 means that we have added left and right node, then do the same for the remaining nodes.

    3. if arr value is -1

    3.a. if index value is 1,i.e., there is no left node then change the index variable to add right node.
    3.b. if index value is 2, i.e, there is no right node then we have repeat this step for the remaining.

    static class Node{
        int data;
        Node left;
        Node right;
        Node(int d){
            data=d;
            left=null;
            right=null;
        }
    }
    

    public static Node constBT(int arr[],int n){

        Node root=null;
        Node curr=null;
        int index=0;
        Queue q=new LinkedList<>();
        for(int i=0;i

提交回复
热议问题