Question:
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
- You may only use constant extra space.
For example,
Given the following binary tree,
1 / \ 2 3 / \ \ 4 5 7
After calling your function, the tree should look like:
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
Anwser 1:
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */class Solution {public: void connect(TreeLinkNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(NULL == root){ return; } TreeLinkNode *cur = root->next; TreeLinkNode *p = NULL; while(cur != NULL){ // find last right node (left or right) if(cur->left) { p = cur->left; break; } if(cur->right){ p = cur->right; break; } cur = cur->next; } if(root->right){ root->right->next = p; } if(root->left){ root->left->next = root->right ? root->right : p; } connect(root->right); // from right to left connect(root->left); }};
注意點:
1) list為非完美二叉樹,右分支可能為空白,因此從right -> left 遍曆
2) 從最右分支開始尋找,且root沒有 left 節點,則找 right 節點
Anwser 2:
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */class Solution {public: void connect(TreeLinkNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(NULL == root){ return; } queue<TreeLinkNode *> Q; // save one line root(s) queue<TreeLinkNode *> Q2; // save next one line root(s), swap with Q Q.push(root); while(!Q.empty()){ TreeLinkNode *tmp = Q.front(); Q.pop(); if(tmp->left) Q2.push(tmp->left); if(tmp->right) Q2.push(tmp->right); if(Q.empty()){ tmp->next = NULL; queue<TreeLinkNode*> tmpQ = Q; // swap queue Q = Q2; Q2 = tmpQ; } else { tmp->next = Q.front(); } } }};
注意點:
1) 新增一個Q2隊列,儲存下一行的全部元素,輔助判斷是最後一個元素(Q為空白)則置為NULL
2) queue隊列實現比遞迴要好
Anwser 3:
/** * Definition for binary tree with next pointer. * struct TreeLinkNode { * int val; * TreeLinkNode *left, *right, *next; * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {} * }; */class Solution {public: void connect(TreeLinkNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if(NULL == root){ return; } queue<TreeLinkNode *> Q; // save one line root(s) Q.push(root); Q.push(NULL); // flag while(!Q.empty()){ TreeLinkNode *tmp = Q.front(); Q.pop(); if(tmp != NULL){ // check flag if(tmp->left) Q.push(tmp->left); if(tmp->right) Q.push(tmp->right); tmp->next = Q.front(); } else { if(Q.empty()){ // pop flag = NULL, then check is empty break; } Q.push(NULL); } } }};
注意點:
對比第二種方法,改進點是每一行結束處,採用NULL作為標誌位