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

117. Populating Next Right Pointers in Each Node II

2016-07-04 17:24 363 查看
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

题意:如同116题,对任意的二叉树找出其结点的next点。
思路:如同,116题,只是在递归时要先递归右树,然后再递归左树。

/**
* 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) {}
* };
*/
/**
* 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 (root == NULL)
return;
if (root->left){
if (root->right)
root->left->next = root->right;
else{
TreeLinkNode *tmp = root->next;
while (tmp){
if (tmp->left || tmp->right){
if (tmp->left){
root->left->next = tmp->left;;
}
else{
root->left->next = tmp->right;
}
break;
}
else
tmp = tmp->next;
}
}
}

if (root->right){
TreeLinkNode *tmp = root->next;
while (tmp){
if (tmp->left || tmp->right){
if (tmp->left){
root->right->next = tmp->left;;
}
else{
root->right->next = tmp->right;
}
break;
}
else
tmp = tmp->next;
}
}
connect(root->right);
connect(root->left);
}
};

思路2:思路1的代码过于冗余,精简一下如下。
/**
* 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) {}
* };
*/
/**
* 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 (root == NULL)
return;

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