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: The general level traversal needs to request the queue, but with the next pointer, we only need to record each layer of the leftmost node, so you can do use constant extra space
classSolution { Public: voidConnect (Treelinknode *root) {Treelinknode*parent; Treelinknode*Current ; Treelinknode* Nextparent =Root; while(nextparent) {//New level startedParent =nextparent; Nextparent= parent->Left ; Current=nextparent; if(!current)return; //Add next pointerCurrent->next = parent->Right ; Current= current->Next; if(!current)return; while(parent->next) {Parent= parent->Next; Current->next = parent->Left ; Current= current->Next; if(!current)return; Current->next = parent->Right ; Current= current->Next; if(!current)return; } } }};
Populating Next right pointers with each Node (Tree; WFS)