GoConqr has a new look! Let us know what you think.

Flashcards

Connect all nodes

Suhas S English 1 card

Cards in this deck (1)

  1. 1Given the root to a binary tree where each node has an additional pointer called sibling (or next), connect the sibling pointer to next node in the same level. Last node in each level should point to the first node of next level in the tree.import java.util.LinkedList;
    import java.util.Queue;
    public class Connect_node_same_level {
    // Node class
    static class Node {
    int data;
    Node left, right, nextRight;
    Node(int data){
    this.data = data;
    left = null;
    right = null;
    nextRight = null;
    }
    };
    // Sets nextRight of all nodes of a tree
    static void connect(Node root)
    {
    Queue q = new LinkedList();
    q.add(root);
    // null marker to represent end of current level
    q.add(root.left);
    // Do Level order of tree using NULL markers
    while (!q.isEmpty()) {
    Node p = q.peek();
    q.remove();
    if (p != null) {
    // next element in queue represents next
    // node at current Level
    p.nextRight = q.peek();
    // push left and right children of current
    // node
    if (p.left != null)
    q.add(p.left);
    if (p.right != null)

Information

Description
Flashcards on Connect all nodes, created by Suhas S on 06/05/2018.
Created by
Suhas S
Views
1
Rating

Feedback

What is it about?

What do you think of the new look?

How do you like it?