您的位置:首页 > Web前端 > Node.js

leetcode116 Populating Next Right Pointers in Each Node

2015-07-13 21:09 651 查看
题意:给一个完全二叉树:

1
/  \
2    3
/ \  / \
4  5  6  7

让左子树的next指针指向右子树,右子树的next继续指向右边,变成了这样:

1 -> NULL
/  \
2 -> 3 -> NULL
/ \  / \
4->5->6->7 -> NULL

思路:唉,英语不行真是醉了,半天没弄明白题意,最后没办法了去找了别人的博客看才明白要干啥。这题的特殊点在于树是完全二叉树,对于其中的一个节点p来说,p->left->next = p->right;p->right->next = p->next->left;明白了这两点这题就解决了,可以用递归,即对root进行这样的操作再对root->left和root->right再做一遍;也可以迭代,附上两种方法的代码。

此题不错,应该多注意一下。

代码1 递归:

void connect(TreeLinkNode *root)
{
if(root == NULL)
return;
if(root->next && root->right)
root->right->next = root->next->left;
if(root->left)
root->left->next = root->right;
connect(root->left);
connect(root->right);
}


代码2 迭代:

void connect(TreeLinkNode *root)
{
TreeLinkNode *pre = root;
TreeLinkNode *cur = NULL;
while(pre)
{
cur = pre;
while(cur && cur->left)
{
cur->left->next = cur->right;
if(cur->next)
cur->right->next = cur->next->left;
cur = cur->next;
}
pre = pre->left;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: