题目描述:
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.
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
和Populating Next Right Pointers in Each Node类似,但是二叉树不一定是完美二叉树,所以在递归之前要先求出子节点指向的同层节点。
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root==NULL) return;
TreeLinkNode* p=root->next;
TreeLinkNode* q=NULL;
while(p!=NULL)
{
if(p->left!=NULL)
{
q=p->left;
break;
}
else if(p->right!=NULL)
{
q=p->right;
break;
}
p=p->next;
}
if(root->left!=NULL&&root->right!=NULL)
{
root->left->next=root->right;
root->right->next=q;
}
else if(root->left!=NULL&&root->right==NULL) root->left->next=q;
else if(root->left==NULL&&root->right!=NULL) root->right->next=q;
connect(root->right);
connect(root->left);
}
};