117. 填充每个节点的下一个右侧节点指针 II 题目有点类似于层序线索化,就是在层序遍历的基础上魔改一下,使得可以获得当前遍历到第几层的信息。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
class Solution { public: void bfs(Node *root) { if(root == NULL) return ; queue<Node*> q; q.push(root); int cnt = 0, tail = 1, num = 0; Node *pre = NULL; while(!q.empty()) { Node *u = q.front(); q.pop(); if(pre) pre->next = u; pre = u; ++ cnt; if(u->left) { q.push(u->left); ++ num; } if(u->right) { q.push(u->right); ++ num; } if(cnt == tail) { cnt = 0; tail = num; num = 0; u->next = NULL; pre = NULL; } } } Node* connect(Node* root) { bfs(root); return root; } };
|
还有一种简单的写法,直接得出当前层节点个数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
class Solution { public: void bfs(Node *root) { if(root == NULL) return ; queue<Node*> q; q.push(root); while(!q.empty()) { Node *pre = NULL; int len = q.size(); for(int i = 0; i < len; i ++) { Node *u = q.front(); q.pop(); if(pre) pre->next = u; pre = u; if(u->left) q.push(u->left); if(u->right) q.push(u->right); } } } Node* connect(Node* root) { bfs(root); return root; } };
|