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
通过上一层的next可以遍历上一层的节点,从而可以依次遍历下一层的节点。
初始条件只有root节点,依次使用next构成的链表遍历上一层,同时构造下一层。
/**
* 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) {
TreeLinkNode *cur = root;
while (cur)
{
TreeLinkNode *head = NULL, *prev = NULL;
while (cur)
{
if (!head) head = cur->left ? cur->left : cur->right;
if (cur->left)
{
if (prev) prev->next = cur->left;
prev = cur->left;
}
if (cur->right)
{
if (prev) prev->next = cur->right;
prev = cur->right;
}
cur = cur->next;
}
cur = head;
}
}
};