logo
down
shadow

How to print the level of every node in binary-tree?


How to print the level of every node in binary-tree?

By : Ali Nadji
Date : October 18 2020, 01:08 AM
Hope this helps I have no clue what language you are using but here is how to print a binary tree in JavaScript.
code :
BinaryTree.prototype.preOrderTraversal = function(node){
    if(node !== null){
        console.log(node.data);
        this.preOrderTraversal(node.left);
        this.preOrderTraversal(node.right);
    }
};

/** 
 * Post traversal prototype function
 *          preforms recursive Postorder traversal on the tree
 *
 * @param  start node
 *
 * @return none
 * @throws none
 **/
BinaryTree.prototype.postOrderTraversal = function(node){
    if(node != null){
        this.postOrderTraversal(node.left);
        this.postOrderTraversal(node.right);
        console.log(node.data);
    }
};

/** 
 * Inorder traversal prototype function
 *          preforms recursive inorder traversal on the tree
 *
 * @param  start node
 *
 * @return none
 * @throws none
 **/
BinaryTree.prototype.inOrderTraversal = function(node){
    if(node != null){
        this.inOrderTraversal(node.left);
        console.log(node.data);
        this.inOrderTraversal(node.right);
    }
};

/** 
 * Depth Frist Search prototype function
 *          preforms Depth First Search on the tree
 *
 * @param  start node
 *
 * @return none
 * @throws none
 **/
BinaryTree.prototype.depthFirstSearch = function(node){
        if(node == null)
            return;

        var stack = [];
        stack.push(node);

        while (stack.length > 0) {
            console.log(node = stack.pop());
            if(node.right!=null) 
                stack.push(node.right);
            if(node.left!=null) 
                stack.push(node.left);          
        }
};

/** 
 * Breadth First Search prototype function
 *          preforms Breadth First Search on the tree
 *
 * @param  start node
 *
 * @return none
 * @throws none
 **/
BinaryTree.prototype.breadthFirstSearch = function(node){
    if(node == null)
        return;

    var queue = [];
    queue.push(node);

    while (queue.length > 0) {
        console.log((node = queue.shift()));
        if(node.left != null) 
            queue.push(node.left);          
        if(node.right != null) 
            queue.push(node.right);

    }
};


Share : facebook icon twitter icon
Writing a method that print binary tree and each node level number

Writing a method that print binary tree and each node level number


By : user70881
Date : March 29 2020, 07:55 AM
To fix this issue I need to write a method that prints a binary tree by using recursion. It must be that the signature of the method will be , Almost what you already did but with the following fix.
code :
public static void level(Node n) {
    level(n, 0);
}

private static void level(Node n, int level) {
   ///..............your logic
   level(n.getLeftSon(), level + 1);
   //...............
   level(n.getRightSon(), level + 1);
}
Binary Tree : Non recursive routine to print ancestor of a node in a Binary Tree?

Binary Tree : Non recursive routine to print ancestor of a node in a Binary Tree?


By : dinomite59
Date : March 29 2020, 07:55 AM
Hope that helps Use a non recursive sub routine to traverse the binary tree( refer to http://en.wikipedia.org/wiki/Tree_traversal#Implementations) and maintain a stack to store the all parent nodes in that array and whenever you pop from stack suitably pop the element from the stack. Finally when you find the element, second topmost element on the stack would be the ancestor.
Time and space complexity of this function to print binary tree level by level

Time and space complexity of this function to print binary tree level by level


By : CHRISTIAN ALBERTO AR
Date : March 29 2020, 07:55 AM
seems to work fine printSpecificLevel_BT is O(n) since it looks at every node in the tree. However, with a simply change (returning when level == 0), you can make it O(min(n, 2^level)).
getHeight is O(n) since it looks at every node in the tree. printBT_LBL calls getHeight once and printSpecificLevel_BT height times, so its complexity is O(n + n*height) = O(n*height).
Print binary tree in level order using only one extra pointer per node

Print binary tree in level order using only one extra pointer per node


By : Sk8er
Date : March 29 2020, 07:55 AM
How to print level-order binary search tree with parent node

How to print level-order binary search tree with parent node


By : Slava Allmighty
Date : March 29 2020, 07:55 AM
With these it helps As noted in the comments, I think you need to be doing a breadth-first search (BFS), keeping track of levels so that you can output a newline when you transition between levels.
Here is code that does the job reasonably robustly. It uses a FIFO queue to record which nodes need processing. The queue is moderately robust, but it stops abruptly if asked to add an element for which there isn't room. Fixing that is doable, but modestly fiddly (dynamic memory allocation, but the hard part is handling the correct copying when the queue array grows but the indexes into the queue are not at the start, which would usually be the case).
code :
#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>

struct node
{
    struct node *left;
    int ID;
    int Grade;
    struct node *right;
};

struct node *newNode(int, int);
struct node *insertNode(struct node *node, int id, int grade);
void printTree(struct node *node);
void printParent(struct node *);

int main(int argc, char **argv)
{
    const char *name = "input.txt";
    if (argc == 2)
        name = argv[1];
    struct node *head = NULL;
    FILE *file = fopen(name, "r");
    if (file == 0)
    {
        fprintf(stderr, "%s: failed to open file %s for reading\n", argv[0], name);
        return 1;
    }
    printf("File: %s\n", name);
    int stdID, grade;
    while (fscanf(file, "%d %d", &stdID, &grade) == 2)
    {
        if (stdID == -1 && grade == -1)
            break;
        printf("Read: %d %d\n", stdID, grade);
        head = insertNode(head, stdID, grade);
        //printf("Tree:\n");
        //printTree(head);
    }
    fclose(file);

    printf("Completed tree:\n");
    printTree(head);
    printf("\n");

    printf("%3d %3d\n", head->ID, head->Grade);
    printf("Parent tree:\n");
    printParent(head);
    printf("\n");

    return 0;
}

struct node *newNode(int id, int grade)
{
    struct node *newnode = malloc(sizeof(struct node));
    newnode->ID = id;
    newnode->Grade = grade;
    newnode->left = newnode->right = NULL;
    return newnode;
}

struct node *insertNode(struct node *node, int id, int grade)
{
    if (node == NULL)
        return newNode(id, grade);
    if (grade < node->Grade)
        node->left = insertNode(node->left, id, grade);
    else if (grade >= node->Grade)
        node->right = insertNode(node->right, id, grade);
    return node;
}

void printTree(struct node *node)
{
    if (node == NULL)
        return;
    printTree(node->left);
    printf("%3d %3d (0x%.12" PRIXPTR ": 0x%.12" PRIXPTR " - 0x%.12" PRIXPTR ")\n",
           node->ID, node->Grade,
           (uintptr_t)node, (uintptr_t)node->left, (uintptr_t)node->right);
    printTree(node->right);
}

/* Structures to manage BFS - breadth-first search */

struct bfs_node
{
    struct node *parent;
    struct node *child;
    char side[4];           /* "L" or "R" plus padding */
    int level;
};

enum { MAX_QUEUE_SIZE = 100 };
struct bfs_queue
{
    struct bfs_node q[MAX_QUEUE_SIZE];
    size_t q_head;
    size_t q_tail;
};

static void bfs_add(struct bfs_queue *q, struct node *parent, struct node *child, int level, char side)
{
    assert(q != 0 && parent != 0 && child != 0);
    assert(parent->left == child || parent->right == child);
    assert(side == 'L' || side == 'R');
    assert(q->q_head < MAX_QUEUE_SIZE && q->q_tail < MAX_QUEUE_SIZE);
    size_t next = (q->q_head + 1) % MAX_QUEUE_SIZE;
    if (next == q->q_tail)
    {
        fprintf(stderr, "Queue is full\n");
        exit(EXIT_FAILURE);
    }
    q->q[q->q_head] = (struct bfs_node){ .parent = parent, .child = child,
                                         .level = level, .side = { side, '\0' } };
    q->q_head = next;
}

static inline void bfs_init(struct bfs_queue *q)
{
    assert(q != 0);
    q->q_head = q->q_tail = 0;
}

static inline int bfs_empty(const struct bfs_queue *q)
{
    assert(q != 0);
    return (q->q_head == q->q_tail);
}

static struct bfs_node *bfs_remove(struct bfs_queue *q)
{
    if (q->q_tail == q->q_head)
    {
        fprintf(stderr, "cannot remove anything from an empty queue\n");
        exit(EXIT_FAILURE);
    }
    assert(q->q_head < MAX_QUEUE_SIZE && q->q_tail < MAX_QUEUE_SIZE);
    size_t curr = q->q_tail;
    q->q_tail = (q->q_tail + 1) % MAX_QUEUE_SIZE;
    return &q->q[curr];
}

void printParent(struct node *node)
{
    if (node == 0)
    {
        printf("Empty tree\n");
        return;
    }

    int level = 0;
    struct bfs_queue q;
    bfs_init(&q);

    if (node->left)
        bfs_add(&q, node, node->left, level + 1, 'L');
    if (node->right)
        bfs_add(&q, node, node->right, level + 1, 'R');

    printf("Level %d: %3d %3d", level, node->ID, node->Grade);

    while (!bfs_empty(&q))
    {
        struct bfs_node *data = bfs_remove(&q);
        assert(data != 0);
        if (data->level != level)
        {
            assert(data->level == level + 1);
            putchar('\n');
            level = data->level;
            printf("Level %d:", level);
        }
        struct node *child = data->child;
        assert(child != 0);
        if (child->left)
            bfs_add(&q, child, child->left, level + 1, 'L');
        if (child->right)
            bfs_add(&q, child, child->right, level + 1, 'R');
        //printf(" %3d %3d (%3d %s)", child->ID, child->Grade, data->parent->ID, data->side);
        printf(" %3d %3d (%3d %s)", child->ID, child->Grade, data->parent->Grade, data->side);
    }
    putchar('\n');
}
File: input.original
Read: 121 40
Read: 456 50
Read: 445 60
Read: 123 70
Read: 677 80
Read: 546 90
Completed tree:
121  40 (0x7FCCD3C00340: 0x000000000000 - 0x7FCCD3C02780)
456  50 (0x7FCCD3C02780: 0x000000000000 - 0x7FCCD3C027A0)
445  60 (0x7FCCD3C027A0: 0x000000000000 - 0x7FCCD3C027C0)
123  70 (0x7FCCD3C027C0: 0x000000000000 - 0x7FCCD3C027E0)
677  80 (0x7FCCD3C027E0: 0x000000000000 - 0x7FCCD3C02800)
546  90 (0x7FCCD3C02800: 0x000000000000 - 0x000000000000)

121  40
Parent tree:
Level 0: 121  40
Level 1: 456  50 ( 40 R)
Level 2: 445  60 ( 50 R)
Level 3: 123  70 ( 60 R)
Level 4: 677  80 ( 70 R)
Level 5: 546  90 ( 80 R)
123 70
456 50
546 90
121 40
445 60
677 80
File: input.req
Read: 123 70
Read: 456 50
Read: 546 90
Read: 121 40
Read: 445 60
Read: 677 80
Completed tree:
121  40 (0x7F99B94027C0: 0x000000000000 - 0x000000000000)
456  50 (0x7F99B9402780: 0x7F99B94027C0 - 0x7F99B94027E0)
445  60 (0x7F99B94027E0: 0x000000000000 - 0x000000000000)
123  70 (0x7F99B9400340: 0x7F99B9402780 - 0x7F99B94027A0)
677  80 (0x7F99B9402800: 0x000000000000 - 0x000000000000)
546  90 (0x7F99B94027A0: 0x7F99B9402800 - 0x000000000000)

123  70
Parent tree:
Level 0: 123  70
Level 1: 456  50 ( 70 L) 546  90 ( 70 R)
Level 2: 121  40 ( 50 L) 445  60 ( 50 R) 677  80 ( 90 L)
305 8
772 51
140 83
877 53
499 74
183 3
240 21
810 49
159 68
977 36
385 3
252 35
163 76
283 12
740 46
829 42
526 51
401 64
726 65
226 3
902 75
File: input-21.txt
Read: 305 8
Read: 772 51
Read: 140 83
Read: 877 53
Read: 499 74
Read: 183 3
Read: 240 21
Read: 810 49
Read: 159 68
Read: 977 36
Read: 385 3
Read: 252 35
Read: 163 76
Read: 283 12
Read: 740 46
Read: 829 42
Read: 526 51
Read: 401 64
Read: 726 65
Read: 226 3
Read: 902 75
Completed tree:
183   3 (0x7FE3795000A0: 0x000000000000 - 0x7FE379500140)
385   3 (0x7FE379500140: 0x000000000000 - 0x7FE379500260)
226   3 (0x7FE379500260: 0x000000000000 - 0x000000000000)
305   8 (0x7FE379500000: 0x7FE3795000A0 - 0x7FE379500020)
283  12 (0x7FE3795001A0: 0x000000000000 - 0x000000000000)
240  21 (0x7FE3795000C0: 0x7FE3795001A0 - 0x7FE3795000E0)
252  35 (0x7FE379500160: 0x000000000000 - 0x000000000000)
977  36 (0x7FE379500120: 0x7FE379500160 - 0x7FE3795001C0)
829  42 (0x7FE3795001E0: 0x000000000000 - 0x000000000000)
740  46 (0x7FE3795001C0: 0x7FE3795001E0 - 0x000000000000)
810  49 (0x7FE3795000E0: 0x7FE379500120 - 0x000000000000)
772  51 (0x7FE379500020: 0x7FE3795000C0 - 0x7FE379500040)
526  51 (0x7FE379500200: 0x000000000000 - 0x000000000000)
877  53 (0x7FE379500060: 0x7FE379500200 - 0x7FE379500080)
401  64 (0x7FE379500220: 0x000000000000 - 0x7FE379500240)
726  65 (0x7FE379500240: 0x000000000000 - 0x000000000000)
159  68 (0x7FE379500100: 0x7FE379500220 - 0x000000000000)
499  74 (0x7FE379500080: 0x7FE379500100 - 0x7FE379500180)
902  75 (0x7FE379500280: 0x000000000000 - 0x000000000000)
163  76 (0x7FE379500180: 0x7FE379500280 - 0x000000000000)
140  83 (0x7FE379500040: 0x7FE379500060 - 0x000000000000)

305   8
Parent tree:
Level 0: 305   8
Level 1: 183   3 (  8 L) 772  51 (  8 R)
Level 2: 385   3 (  3 R) 240  21 ( 51 L) 140  83 ( 51 R)
Level 3: 226   3 (  3 R) 283  12 ( 21 L) 810  49 ( 21 R) 877  53 ( 83 L)
Level 4: 977  36 ( 49 L) 526  51 ( 53 L) 499  74 ( 53 R)
Level 5: 252  35 ( 36 L) 740  46 ( 36 R) 159  68 ( 74 L) 163  76 ( 74 R)
Level 6: 829  42 ( 46 L) 401  64 ( 68 L) 902  75 ( 76 L)
Level 7: 726  65 ( 64 R)
Related Posts Related Posts :
  • Django - stop synchronisation between different variables based on filters on same object
  • Using python together with knitr
  • Difference between <type 'classobj'>, <type 'object'>?
  • what is top level module in Python?
  • Is there a query method or similar for pandas Series (pandas.Series.query())?
  • Deleting DataFrame row in Pandas where column value in list
  • Python Integer and String Using
  • Python requests: URL with percent character
  • Why ActionChains(driver).move_to_element(elem).click().perform() twice
  • Why is my code not compiling
  • How to equalize the size of two numpy arrays
  • Hive Server 2 error on python connect with hiveserver2
  • TypeError: argument 1 must have a "write" method
  • Python, read uart and post to MQTT, has extra spaces
  • test getting skipped in pytest
  • Python: from list to enumerated list to pass to lambda reduce function
  • f[1] raised exception TypeError: 'int' object is not subscriptable
  • how to make a random list in python3
  • Keeping Python from spacing after breaking a line when printing a List
  • Create a temporary table in python to join with a sql table
  • How to update a specific line in a file in python?
  • Google PubSub python client returning StatusCode.UNAVAILABLE
  • Error in regex substring match in a list in python
  • Pandas groupby() on one column and then sum on another
  • How to use multiple "or" in python code
  • spider = cls(*args, **kwargs) TypeError: __init__() got an unexpected keyword argument '_job'
  • Python, Django LDAP: detecting Authentication failed reasoning
  • Is it good to define a function in a function python
  • Zeep : Need to convert this sample soap request
  • How to render a template and send a file simultaneously with flask
  • Create new column in dataframe with match values from other dataframe
  • Group the values using one column and return the one having max value in other column using pandas dataframe
  • Python3 tkinter analog gauge
  • How to display all the data which is groupby "Cause" from 1981 to 1992 in python pandas?
  • Scrape content in json format - Python
  • How to replace pandas columns with the same name in to another dataframe?
  • Trying to build a proxy with aiohttp
  • Compound interest calculator loops
  • how to create a raw string when it's last character is a `\` in python
  • Scrapy - how can I split the data in this table?
  • Making post requests in python
  • How can I manipulate shapes (colors) in PowerPoint using Python and win32com.client?
  • Get sorted output for os.walk()
  • Pandas Mapping Column
  • How to remove border of microsoft word in text image in opencv with python?
  • why not always use map if its faster than the rest (list comprehension, loop (various variants))?
  • Trying to download a directory with requests
  • Django Django model “doesn't declare an explicit app_label” because of project's init.py file
  • Comparing 2 arrays using numpy and allocating values to a third array
  • How to do change the recieved SQL output format, in python
  • Python: how to write binary data to the stdout so that bash script can use process substitution?
  • How to combine two lists to get a new list of the shape as mentioned in description
  • Run-time Complexity for two algorithms (Big O notation calculation)
  • jupyter SSL: WRONG_VERSION_NUMBER
  • Import of csv data rows and columns when specyfing delimiter
  • Error in texting automated message in whatsapp using python
  • Why my model work ok with test data from train_test_split while doesn't with the new data?
  • Python Networkx: How to "redraw" graph after every iteration?
  • How to read a large json in pandas?
  • Protobuf Message Constructor
  • shadow
    Privacy Policy - Terms - Contact Us © soohba.com