leetcode question 116: Populating Next Right Pointers in Each Node
阿新 • • 發佈:2018-12-13
問題:
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.
- Recursive approach is fine, implicit stack space does not count as extra space for this problem.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
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
分析:
這道題叫我們對一課完全二叉樹進行操作,如果當前節點右邊有節點,就將next指標指向它,否則就置為空。我是用兩個list來完成的,一個用來儲存當前層的節點,另一個用來儲存下一層的節點(按順序),當前層處理完後,就將下一層的節點賦給當前層,一直到葉子節點。
程式碼:
/**
* 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) {
//為空直接跳出
if(root == NULL){
return;
}
//當前層
list<TreeLinkNode*> current;
TreeLinkNode* cur_node;//當前節點
TreeLinkNode* temp_node;//右邊的節點(沒有時為空)
current.push_back(root);
while( true ){
list<TreeLinkNode*> temp;
while( current.size() != 0 ){
cur_node = current.front();
current.pop_front();
if(cur_node->left != NULL){
temp.push_back(cur_node->left);
temp.push_back(cur_node->right);
}
//當前節點右邊還有節點
if(current.size()!=0){
temp_node = current.front();
cur_node->next = temp_node;
}else{
cur_node->next = NULL;
}
}
current = temp;
if( current.size() == 0 && temp.size() == 0 ){
break;
}
}
}
};