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
思路:
还是要保存每行的第一个节点,可以用 栈 或 其他实现;连接的过程中要保存上一个节点,因为父节点之间可能不是连在一起的。 也可以使用递归实现。
class Solution {
public:
void connect(TreeLinkNode *root) {
if (root == NULL)
return;
stack<TreeLinkNode *> MyStack;
MyStack.push(root);
while (!MyStack.empty()) {
TreeLinkNode *head = MyStack.top();
MyStack.pop();
TreeLinkNode *temp = head;
while (temp != NULL) {
if (temp->left == NULL && temp->right == NULL) {
temp = temp->next;
continue;
}
if (temp->left != NULL)
MyStack.push(temp->left);
else
MyStack.push(temp->right);
break;
}
temp = NULL;
while (head != NULL) {
if (head->left != NULL && head->right != NULL) {
if (temp != NULL)
temp->next = head->left;
head->left->next = head->right;
temp = head->right;
}
else if (head->left != NULL || head->right != NULL) {
if (temp != NULL) {
temp->next = head->left != NULL ? head->left : head->right;
temp = temp->next;
}
else
temp = head->left != NULL ? head->left : head->right;
}
head = head->next;
}
}
}
};