Populating Next Right Pointers in Each Node
描述:
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
解法:
本题比较简单,注意 判断NULL的情况。
代码如下:
void connect(TreeLinkNode *root) {
if( root == NULL) return ;
TreeLinkNode *preP = root;
TreeLinkNode *curP = root->left;
root->next = NULL;
while( curP )
{
TreeLinkNode *tempP = preP;
while( curP )
{
if( preP == NULL){
curP->next = NULL;
curP = NULL;
}else if( curP == preP->left){
curP->next = preP->right;
curP = curP->next;
preP = preP->next;
}else{
curP->next = preP->left;
curP = curP->next;
}
}
preP = tempP->left;
curP = preP->left;
}
}
Populating Next Right Pointers in Each Node II
链接:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
描述:
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
解法:
本题比上一题,复杂,非递归解法如下:
void connect(TreeLinkNode *root) {
if(root == NULL) return ;
root->next = NULL;
TreeLinkNode *prep = root;
TreeLinkNode *curp;
if(root->left)
curp = root->left;
else
curp = root->right;
while(curp)
{
TreeLinkNode *tempcurp=curp;
while(curp)
{
if(prep == NULL)
{
curp->next = NULL;
break;
}else if( curp == prep->right)
{
prep = prep->next;
}else if( curp == prep->left)
{
if( prep->right )
{
curp->next = prep->right;
curp = curp->next;
}
prep = prep->next;
}else{
while(prep && prep->left == NULL && prep->right == NULL)
prep = prep->next;
if(prep){
if(prep->left)
curp->next = prep->left;
else
curp->next = prep->right;
curp = curp->next;
}
}
}
prep = tempcurp;
while(prep && prep->left == NULL && prep->right == NULL)
prep = prep->next;
if(prep && prep->left)
curp = prep->left;
else if(prep && prep->right)
curp = prep->right;
else
break;
}
}
递归解法:
void connect(TreeLinkNode *root) {
if(root == NULL) return;
TreeLinkNode dumy(-1);
//dumy.next = root;
for(TreeLinkNode *cur = root, *pre = &dumy; cur ; cur = cur->next){
if(cur->left != NULL){
pre->next = cur->left;
pre = pre->next;
}
if(cur->right != NULL){
pre->next = cur->right;
pre = pre->next;
}
}
connect(dumy.next);
}