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既然是满二叉树就不需要考虑太多,如果一个结点有左子树,那么在盖层的结点均有左右子树,只要将他们连接起来即可
class Solution {
public:
void connect(TreeLinkNode *root) {
go(root);
}
void go(TreeLinkNode* node){
if(node==NULL)
return;
TreeLinkNode* head = new TreeLinkNode(-1);
TreeLinkNode* tail = head;
while(node!=NULL){
if(node->left!=NULL){
tail->next = node->left;
tail->next->next = node->right;
tail = tail->next->next;
node = node->next;
}else
break;
}
go(head->next);
}
};
更加通用的方法,使用与Populating Next Right Pointers in Each Node II 相同的代码也可解决问题,即用个虚拟头结点
class Solution {
public:
void connect(TreeLinkNode *root) {
dfs(root);
}
void dfs(TreeLinkNode* node){
if(node==NULL)
return;
TreeLinkNode* head = new TreeLinkNode(-1);
TreeLinkNode* tail = head;
while(node!=NULL){
if(node->left!=NULL){
tail->next = node->left;
tail = tail->next;
}
if(node->right!=NULL){
tail->next = node->right;
tail = tail->next;
}
node= node->next;
}
dfs(head->next);
}
};