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
Hide TagsTree Depth-first SearchHas you met this question in a real interview? Yes No
Discuss
The problem was put up because of the words in the title: You could use constant extra space
This means that deep search is not possible, because recursion requires a stack, so the spatial complexity will be O (LOGN). No doubt wide search also can not be used, because the queue is also occupied space, space occupancy is also higher than O (LOGN)
Difficult to be here, deep search and wide search can not be used, how to complete the tree traversal?
I got the first response to the topic is: With a wide search, and then found that the wide search can not be used, then made a difficult.
Read some hints, there are strokes: the core is still wide search, but we can borrow the next pointer, do not need to queue to complete the breadth of searching.
If the next pointer of all nodes in the current layer is set, then the next pointer of all nodes in the next layer can be set in turn.
classSolution { Public: voidConnect (Treelinknode *root) { if(Root = =NULL)return; Treelinknode* Curlayer = root;//The leftmost node of the layer while(curlayer) {Treelinknode* Curnode =Curlayer; while(Curnode && Curnode->left)//Curnode is not a leaf node{Treelinknode* left = curnode->Left ; Treelinknode* right= curnode->Right ; Left->next =Right ; if(curnode->next) right->next = curnode->next->Left ; Curnode= curnode->Next; } Curlayer= curlayer->Left ; } }};
[Leetcode] Populating Next right pointers in each Node