Skip to content

Commit

Permalink
leetcode
Browse files Browse the repository at this point in the history
  • Loading branch information
arkingc committed Jun 6, 2023
1 parent 484cc91 commit 406e79e
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions 数据结构与算法/算法题总结.md
Original file line number Diff line number Diff line change
Expand Up @@ -12651,6 +12651,68 @@ private:
};
```

以树构建graph(节点与左右子节点连通),然后从target节点开始以BFS的方式遍历graph,深度为K的节点就是结果:
```
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> distanceK(TreeNode* root, TreeNode* target, int k) {
unordered_map<TreeNode*, vector<TreeNode*> > m;
buildGraph(root, m);

deque<TreeNode *> res;
res.push_back(target);

while(k && !res.empty()) {
int sz = res.size();
--k;
for (int i = 0; i < sz; i++) {
TreeNode *nd = res.front();
res.pop_front();

for (TreeNode *next : m[nd]) {
if (m.find(next) != m.end()) {
res.push_back(next);
}
}
m.erase(nd); // remove visited node
}
}

vector<int> res_values(res.size());
for (int i = 0; i < res.size(); i++) {
res_values[i] = res[i]->val;
}
return res_values;
}
private:
void buildGraph(TreeNode *nd, unordered_map<TreeNode*, vector<TreeNode*> > &m) {
if (!nd) {
return;
}

if (nd->left) {
m[nd].push_back(nd->left);
m[nd->left].push_back(nd);
buildGraph(nd->left, m);
}
if (nd->right) {
m[nd].push_back(nd->right);
m[nd->right].push_back(nd);
buildGraph(nd->right, m);
}
}
};
```

<br>
<br>

Expand Down

0 comments on commit 406e79e

Please sign in to comment.