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

Populating Next Right Pointers in Each Node II <leetcode>

2014-09-09 18:58 337 查看
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

算法:该题和第一个题的变种,不过揭发是一样的,首先也是只要考虑当前节点,然后递归就行了,要点有二:1、当该节点左子树或右子树的右边的第一个节点   2、递归时要先算右子树,因为左子树的处理递归时会用到右边已经形成的结果,代码如下:


/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
*  int val;
*  TreeLinkNode *left, *right, *next;
*  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
void connect(TreeLinkNode *root) {
if(NULL==root)  return;
if(NULL!=root->left)
{
if(NULL!=root->right)
{
root->left->next=root->right;
}
else  root->left->next=find(root->next);
}
if(NULL!=root->right)
{
root->right->next=find(root->next);
}

connect(root->right);
connect(root->left);
}

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