解题思路
与populating-next-right-pointers-in-each-node一样,代码一致,也可通过。
代码
#include<queue>
#include<map>
class Solution {
public:void connect(TreeLinkNode *root) {queue<TreeLinkNode *>q;vector<TreeLinkNode *>v;map<TreeLinkNode *,int>m;if(root != NULL){q.push(root);m[root] = 1;}while(!q.empty()){TreeLinkNode *tmp = q.front();q.pop();v.push_back(tmp);if(tmp->left){m[tmp->left] = m[tmp] + 1;q.push(tmp->left);}if(tmp->right){m[tmp->right] = m[tmp] + 1;q.push(tmp->right);}}for(int i = 0;i < v.size();i++){if(i + 1 == v.size() || m[v[i]] != m[v[i + 1]])v[i]->next = NULL;elsev[i]->next = v[i + 1];}}
};