Populating Next Right Pointers in Each Node
OJ: https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node/
Given a binary tree
struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}
Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL
.
Initially, all next pointers are set to NULL
.
Note:
- You may only use constant extra space.
- You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).
For example, Given the following perfect binary tree,
1
/ \
2 3
/ \ / \
4 5 6 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> 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) {
TreeLinkNode *p = root;
while(p && p->left) {
p->left->next = p->right;
TreeLinkNode *pre = p, *cur = p->next;
while(cur) {
pre->right->next = cur->left;
cur->left->next = cur->right;
pre = cur;
cur = cur->next;
}
p = p->left;
}
}
};
Populating Next Right Pointers in Each Node II
OJ:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
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
思想同上: 但是下一层最开始结点和连接过程中链表的第一个结点不易确定,所以需要设定两个变量来保存。
/**
* 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 *curListNode, *startNode, *curNode;
startNode = root;
while(startNode) {
curNode = startNode;
startNode = curListNode = NULL;
while(curNode) {
if(curNode->left) {
if(startNode == NULL) startNode = curNode->left;
if(curListNode == NULL) curListNode = curNode->left;
else { curListNode->next = curNode->left; curListNode = curListNode->next; }
}
if(curNode->right) {
if(startNode == NULL) startNode =curNode->right;
if(curListNode == NULL) curListNode = curNode->right;
else { curListNode->next = curNode->right; curListNode = curListNode->next; }
}
curNode = curNode->next;
}
}
}
};