来看这个题,https://leetcode.com/problems/…,要求常数空间,想了想,没想到,找了答案,是这样
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) {
return;
}
TreeLinkNode dummy(-1);
for (TreeLinkNode *prev = &dummy, *curr = root; curr; curr = curr->next) {
if (curr->left) {
prev->next = curr->left;
prev = prev->next;
}
if (curr->right) {
prev->next = curr->right;
prev = prev->next;
}
}
connect(dummy.next);
}
};
脑子里跑了一遍,感觉理解不了啊,想不通的是,5->7 的那个连接是怎么连上去的
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
如果你看上面的代码可以理解 5->7 的连接,后面的就不用看了,不行的话,看这个,写了一个 debug 代码
#include <stdio.h>
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) {
if (!root) {
return;
}
TreeLinkNode dummy(-1);
for (TreeLinkNode *prev = &dummy, *curr = root; curr; curr = curr->next) {
if (curr->left) {
printf("connecting %p(%d) to %p(%d)\n", prev, prev?prev->val:0, curr->left, curr->left->val);
prev->next = curr->left;
prev = prev->next;
}
if (curr->right) {
printf("connecting %p(%d) to %p(%d)\n", prev, prev?prev->val:0, curr->right, curr->right->val);
prev->next = curr->right;
prev = prev->next;
}
}
connect(dummy.next);
}
};
void print(TreeLinkNode* node) {
printf("%p(%d) left:%p(%d) right:%p(%d) next:%p(%d)\n", node, node->val,
node->left, node->left?node->left->val:0,
node->right, node->right?node->right->val:0,
node->next, node->next?node->next->val:0);
}
void inOrder(TreeLinkNode* root) {
if (!root) {
return;
}
print(root);
inOrder(root->left);
inOrder(root->right);
}
int main() {
TreeLinkNode root(1), two(2), three(3), four(4), five(5), six(6), seven(7);
root.left = &two;
root.right = &three;
two.left = &four;
two.right = &five;
three.right = &seven;
inOrder(&root);
printf("-----------------------------\n");
Solution solution;
solution.connect(&root);
printf("-----------------------------\n");
inOrder(&root);
return 0;
}
看一下输出
0012FF1C(1) left:0012FF04(2) right:0012FEEC(3) next:00000000(0) 0012FF04(2) left:0012FED4(4) right:0012FEBC(5) next:00000000(0) 0012FED4(4) left:00000000(0) right:00000000(0) next:00000000(0) 0012FEBC(5) left:00000000(0) right:00000000(0) next:00000000(0) 0012FEEC(3) left:00000000(0) right:0012FE8C(7) next:00000000(0) 0012FE8C(7) left:00000000(0) right:00000000(0) next:00000000(0) ----------------------------- connecting 0012FD84(-1) to 0012FF04(2) connecting 0012FF04(2) to 0012FEEC(3) connecting 0012FC6C(-1) to 0012FED4(4) connecting 0012FED4(4) to 0012FEBC(5) connecting 0012FEBC(5) to 0012FE8C(7) ----------------------------- 0012FF1C(1) left:0012FF04(2) right:0012FEEC(3) next:00000000(0) 0012FF04(2) left:0012FED4(4) right:0012FEBC(5) next:0012FEEC(3) 0012FED4(4) left:00000000(0) right:00000000(0) next:0012FEBC(5) 0012FEBC(5) left:00000000(0) right:00000000(0) next:0012FE8C(7) 0012FEEC(3) left:00000000(0) right:0012FE8C(7) next:00000000(0) 0012FE8C(7) left:00000000(0) right:00000000(0) next:00000000(0)
脑子里再过一遍,应该就能理解了