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.
For example,
Given the following binary tree,
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
TreeLinkNode* nextFind(TreeLinkNode *root)
{
if(!root)
return NULL;
root = root->next;
TreeLinkNode *retAdd = NULL;
while(root)
{
if(root->left)
{
retAdd = root->left;
break;
}
if(root->right)
{
retAdd = root->right;
break;
}
root = root->next;
}
return retAdd;
}
void connectR(TreeLinkNode * root)
{
if(!root)
return;
if(root->left)
{
if(root->right)
{
root->left->next = root->right;
root->right->next = nextFind(root);
connectR(root->right);
}
else
{
// no right
root->left->next = nextFind(root);
connectR(root->right);
}
connectR(root->left);
}
else if(root->right)
{
root->right->next = nextFind(root);
connectR(root->right);
}
else
{
connectR(nextFind(root));
}
}
void connect(TreeLinkNode * root) {
if(!root)
return;
root->next = NULL;
connectR(root);
}
No comments:
Post a Comment