logo
down
shadow

How to construct a tree given a level-order traversal?


How to construct a tree given a level-order traversal?

By : user2949896
Date : November 17 2020, 04:28 AM
With these it helps The easiest, that worked for me, was to first build the tree, and only then to fork the tree and make the process tree.
For the purpose of building a tree I made a structure which will represent the node:
code :
typedef struct _node {
    int val; // how many children the node has
    struct _node **children; // all the children of the node
} node, *pNode;
typedef struct _queue {
    pNode el;
    struct _queueInt *next;
} queue, *pQueue;


Share : facebook icon twitter icon
Level Order tree Traversal for a generic tree, displaying the tree level by level

Level Order tree Traversal for a generic tree, displaying the tree level by level


By : Ad Wolters
Date : March 29 2020, 07:55 AM
Any of those help I would like to display the tree structure level by level. My current code does a BFS or Level Order Traversal but I cannot get the output to display the tree structure like a tree See current output and Expected output. , only need to keep track of current level and next level.
code :
static void displayBFS(NaryTreeNode root) {
    int curlevel = 1;
    int nextlevel = 0;

    LinkedList<NaryTreeNode> queue = new LinkedList<NaryTreeNode>();
    queue.add(root);

    while(!queue.isEmpty()) { 
        NaryTreeNode node = queue.remove(0);

        if (curlevel == 0) {
            System.out.println();
            curlevel = nextlevel;
            nextlevel = 0;
        }

        for(NaryTreeNode n : node.nary_list) {
            queue.addLast(n);
            nextlevel++;
        }

        curlevel--;
        System.out.print(node.data + " ");
    } 
}
How to construct a binary tree from just the level order traversal string

How to construct a binary tree from just the level order traversal string


By : jon
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Consider a binary tree with the following properties: , Conceptually more simpler I think.
code :
import java.util.LinkedList;
import java.util.Queue;

class WeirdBinaryTree
{
static class Node
{
    private Node right;
    private Node left;
    private int weirdValue;

    public void setWeirdValue(int value)
    {
        weirdValue=value;
    }
}

private static Node makeTree(String str)throws Exception
{
    char[] array=str.toCharArray();
    Node root=new Node();
    Queue<Node> list=new LinkedList();
    list.add(root);
    int i=0;
    Queue<Node> nextList=new LinkedList<Node>();
    while(!list.isEmpty())
    {
        if(array[i++]=='1')
        {                
                Node temp=list.poll();
                temp.left=new Node();
                temp.right=new Node();
                temp.setWeirdValue(1);
                nextList.add(temp.left);
                nextList.add(temp.right);       
        }
        else
        {
            list.poll();
        }
        if(list.isEmpty())
        {
            list=nextList;
            nextList=new LinkedList<Node>();
        }
    }
    return root;
}

private static void postTraversal(Node localRoot)
{
    if(localRoot!=null)
    {
        postTraversal(localRoot.left);
        postTraversal(localRoot.right);
        System.out.print(localRoot.weirdValue);
    }
}

public static void main(String[] args)throws Exception 
{
    postTraversal(makeTree("111001000"));
}
}
How to construct a binary tree using a level order traversal sequence

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


By : ERMANNO
Date : March 29 2020, 07:55 AM
will help you Assume using array int[]data with 0-based index, we have a simple function to get children:
code :
int getLeftChild(int index){
   if(index*2 + 1 >= data.length)
      return -1;// -1 Means out of bound
   return data[(index*2) + 1];
}
int getRightChild(int index){
   if(index*2 + 2 >= data.length)
      return -1;// -1 Means out of bound           
   return data[(index*2) + 2];
}
     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;
    } 
How to construct complete tree from level order traversal

How to construct complete tree from level order traversal


By : F Silva
Date : March 29 2020, 07:55 AM
With these it helps Looks like a simple insertion to me. If you have the values of the nodes in the order you specified just run a recursive insertion.
code :
void insert(node_t **root, int val)
{
      if (*root == NULL) {
            *root = malloc(sizeof(node_t));
            *root->val   = val;
            *root->left  = NULL;
            *root->right = NULL;
       } else if ((*root)->val >= val) {
            insert(&(*root)->left, val);
       } else {
            insert(&(*root)->right, val);
       }
 }
int main (void)
{
     node_t *root = NULL;
     // call this with each value in
     insert(&root, <your value>);
 }
construct a binary tree from in-order and level-order traversal

construct a binary tree from in-order and level-order traversal


By : kcn
Date : March 29 2020, 07:55 AM
To fix the issue you can do I think you are on the right track. below is a working code which I worked out using your data.
Related Posts Related Posts :
  • Why do I get the error "bash: ./a.out: Permission denied" when I execute a C program in Linux mint 15
  • syntax of sigchld and its declaration
  • error using g_idle_add() in C++, same thing works in C
  • why if else or nested if else are called single statement in C
  • How do I interpret this printf in C
  • load the functions of a shell script without executing it
  • Is FilterSendNetBufferLists handler a must for an NDIS filter to use NdisFSendNetBufferLists?
  • How to write to flash memory using inline assembly?
  • More Return Statements vs. More Indentation
  • How to show an image on a PictureBox from resource?
  • Having malloced some memory,I could't calculator the proper size of the memories I malloced.I don't know why
  • What is the main difference between integer pointer and character pointer?
  • Why are some functions declared extern and header file not included in source in Git source code?
  • what is the use of fflush(stdin) in c programming
  • Is it safe to return file File descriptor locally allocated from another function In C
  • Changing undefined values of an array
  • What does an empty parameter list mean?
  • using strtol on a string literal causing segmentation fault
  • Same structure objects memory overlap?
  • C-Linux-Any way to pass command "history" to Linux shell?
  • Using #define in defining string size C
  • How to use thread pool and message queues in Multithreaded Matrix Multiplication?
  • Can't find how to select path to run a C program
  • Automatic variable in C not initialized but given fixed value within loop
  • main() function defined without return type gives warning
  • Output of following code with integer, float, char variable
  • why buffer memory allocation error in opencl
  • Why am I getting this error during run-time?
  • Strange behaviour of the pow function
  • task in increment , decrement , printf() , why these are evaluated in this manner in C
  • 28 extra bytes in bss
  • Waiting for multiple events without polling
  • Why are my variables reporting as "undeclared identifier" when compiling?
  • Correct AddNode function but somehing happens when I printf
  • When I traverse in the splay tree, then now which one is root?
  • Data type conversion in Postfix evaluation
  • No output in terminal (Head First C)
  • Data writes over after realloc
  • function: findnextchar() doesn't work
  • Getting file-size property from Nautilus
  • Forward declare entities in C standard library?
  • Static array in C
  • Function signature indicates return type void*, but returns pointer of a different type
  • How do I measure time per thread in C?
  • Online judgeProblem (Wrong Answer)
  • Use function pointer initialized in other source file
  • last line of file is duplicated using fscanf
  • How to print files with same month of modification using directory in c?
  • ADT Circular Queue enqueue and dequeue
  • What events can cause ferror to return non-zero?
  • Accessing dynamically allocated structure received through socket
  • Vim with C Conditional Parsing
  • C can pointers be aligned with any other data type?
  • sdcc inline asm() not working
  • I/O - Manipulation of C Strings
  • sscanf 1 byte hex data without overflow
  • Avoid division by zero in C when taking log with respect to a random number
  • C - memory corruption with threads
  • Why does my program sometimes returns 0xc0000005 and sometimes runs well?
  • C - Dynamic array handling advice
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org