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
Idea: A node is required to record the leftmost starting point of each layer, and a cur pointer is required to move from left to right in each layer to concatenate the next pointer
1 Public voidConnect (Treelinknode root) {2 if(Root = =NULL) {3 return;4 }5Treelinknode Lefthead =Root;6 while(Lefthead! =NULL&& Lefthead.left! =NULL) {7Treelinknode cur =Lefthead;8 while(cur! =NULL) {9Cur.left.next =Cur.right;TenCur.right.next = Cur.next = =NULL?NULL: Cur.next.left; OneCur =Cur.next; A } -Lefthead =Lefthead.left; - } the}
Ii:
Follow up to Problem "populating Next right pointersin each Node".
What if the given tree could is any binary tree? Would your previous solution still work?
Note:
For example,
Given The following binary tree,
1 / 2 3 /\ 4 5 7
After calling your function, the tree is should look like:
1, NULL / 2, 3, null /\ 4-> 5, 7, NULL
Idea: The basic ideas are the same. But because this is not a perfect binary tree. So when you concatenate the next pointer, you have to find a way to record the previous point of the current point, and we introduce the pre pointer.
Also, the starting point of each layer is not necessarily the leftmost position of the layer. So use dummy node to record the starting point.
1 Public voidConnect (Treelinknode root) {2 if(Root = =NULL) {3 return;4 }5Treelinknode Leftnode =Root;6 while(Leftnode! =NULL) {7Treelinknode dummy =NewTreelinknode (0);8Treelinknode pre =dummy;9Treelinknode cur =Leftnode;Ten while(cur! =NULL) { One if(Cur.left! =NULL) { APre.next =Cur.left; -Pre =Pre.next; - } the if(Cur.right! =NULL) { -Pre.next =Cur.right; -Pre =Pre.next; - } +Cur =Cur.next; - } +Leftnode =Dummy.next; A } at}
Populating Next right pointers in each Node I && II