当前位置: 代码迷 >> 综合 >> leetcode练习题 populating-next-right-pointers-in-each-node-ii
  详细解决方案

leetcode练习题 populating-next-right-pointers-in-each-node-ii

热度:71   发布时间:2023-12-15 10:03:19.0

解题思路

与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];}}
};
  相关解决方案