Karteikarten
Connect all nodes
Karten in diesem Stapel (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)
Informationen
- Beschreibung
- Karteikarten am Connect all nodes, erstellt von Suhas S am 06/05/2018.
- Erstellt von
- Suhas S
- Aufrufe
- 1
- Bewertung