Description
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.
Note:
You may only use constant extra space.
You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example,
Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
Explain
這道題的意思就是讓樹的每一層的每個節點連接成一個鏈表。而且空間復雜度是O(1),好用的隊列的層序遍歷一下子就被限制了。幸好這道題給我們的樹是完美二叉樹。我們只要在上一層時將下一層的節點連接好就行了,因為上一層已經是被連接好的了,是有序的,遍歷上一層,將下一層的節點連接起來就好了。只是在遍歷每一層時將下一層的頭結點保存下來,如果頭結點為空,那么我們的算法就完結了。
Code
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
TreeLinkNode* start = root, *temp;
while(start) {
temp = start;
start = start->left;
while(temp) {
if (temp->left && temp->right) {
temp->left->next = temp->right;
if (temp->next) {
temp->right->next = temp->next->left;
}
}
temp = temp->next;
}
}
}
};