116. 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 toNULL
.
Initially, all next pointers are set toNULL
.
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
S: 利用next节点进行row level traversal
void connect(TreeLinkNode *root) {
TreeLinkNode* rowStart = root;
TreeLinkNode* cur = root;
while(cur && cur->left) {
cur->left->next = cur->right;
if(cur->next) {
cur->right->next = cur->next->left;
cur = cur->next;
}
else {
cur = rowStart->left;
rowStart = cur;
}
}
}
117. 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
S:将left node, right node平等对待,只管pre和cur。
pre为要populate next right的节点,cur为pre上一层节点,pre->next可能为cur->left或cur->right
nextRow.next存储cur下一行最左节点,Pre初始化为nextRow可避免第一行的特殊处理
void connect(TreeLinkNode *root) {
TreeLinkNode* cur = root;
TreeLinkNode nextRow(0);
TreeLinkNode* pre = &nextRow;
while (cur) {
if (cur->left) {
pre->next = cur->left;
pre = cur->left;
}
if (cur->right) {
pre->next = cur->right;
pre = cur->right;
}
if (cur->next) {
cur = cur->next;
}
else {//end of this row, reinitiate
cur = nextRow.next;
nextRow.next = NULL;
pre = &nextRow;
}
}
}