问题描述
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
1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL
解决思路
116其实就是117的一个特例。所以这里直接贴出117的解决办法就好了。主要是利用递归。一层一层连接,每一层都找到开始的节点,然后用这个节点递归。其实这道题主要是情况讨论题,不难。- 代码
/**
* 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) {
helper(root);
}
void helper(TreeLinkNode *root) {
if (!root)
return;
TreeLinkNode *cur = root;
TreeLinkNode *next_pre = NULL,*next_begin = NULL;
while(cur != NULL) {
if (!cur->left && !cur->right) {
cur = cur->next;
} else if (cur->left && cur->right) {
if (!next_pre) {
cur->left->next = cur->right;
next_pre = cur->right;
next_begin =cur->left;
} else {
next_pre->next = cur->left;
cur->left->next = cur->right;
next_pre = cur->right;
}
cur = cur->next;
} else if (!cur->right) {
if (!next_pre) {
next_pre = cur->left;
next_begin = cur->left;
} else {
next_pre->next = cur->left;
next_pre = cur->left;
}
cur = cur->next;
} else {
if (!next_pre) {
next_pre = cur->right;
next_begin = cur->right;
} else {
next_pre->next = cur->right;
next_pre = cur->right;
}
cur = cur->next;
}
}
helper(next_begin);
}
};