Given a binary tree
struct Treelinknode { treelinknode *left; Treelinknode *right; Treelinknode *next; }
Populate each of the next pointer to the next right node. If There is no next right node, the next pointer should are set to NULL .
Initially, all next pointers is set to NULL .
Note:
- Constant extra space.
- You could assume that it was a perfect binary tree (ie, all leaves was at the same level, and every parent had both children).
For example,
Given the following perfect binary tree,
1 / 2 3 /\ / 4 5 6 7
After calling your function, the tree is should look like:
1, NULL / 2, 3, null /\ / 4->5->6->7, NULL
Change the structure of the tree.
The first use of the queue, not very soon.
/*** Definition for binary tree with next pointer. * public class Treelinknode {* Int. val; * Treelinknode left , right, next; * Treelinknode (int x) {val = x;} }*/ Public classSolution { Public voidConnect (Treelinknode root) {if(Root = =NULL) return ; Queue Queue=NewLinkedlist<treelinknode>(); Queue.add (root); while( !Queue.isempty ()) {treelinknode node=(Treelinknode) queue.poll (); if(Node.left! =NULL) {Node.left.next=Node.right; if(Node.next! =NULL) Node.right.next=Node.next.left; Queue.add (Node.left); Queue.add (Node.right); } } }}
The fastest is achieved without using the queue.
/*** Definition for binary tree with next pointer. * public class Treelinknode {* Int. val; * Treelinknode left, Right, Next; * Treelinknode (int x) {val = x;} }*/ Public classSolution { Public voidConnect (Treelinknode root) {if(Root = =NULL) return ; Treelinknode Node1= Root,node2 =Root; while(Node2.left! =NULL) {Node1=Node2.left; while(Node2.next! =NULL) {Node2.left.next=Node2.right; Node2.right.next=Node2.next.left; Node2=Node2.next; } Node2.left.next=Node2.right; Node2=Node1; } }}
Leetcode populating Next right pointers in each Node-----java