863. All Nodes Distance K in Binary Tree
Approach
题目大意:给一个结点target求距离target为K的结点值。
解决方法:将树转化为图,对图进行DFS
Code
C++
class Solution {
public:
unordered_map<TreeNode*, vector<TreeNode*>>unmp;
vector<int>vec;
vector<int> distanceK(TreeNode* root, TreeNode* target, int K) {
if (root == nullptr)return vector<int>();
TreeTransferGraph(root);
dfs(target, target, 0, K);
return vec;
}
void TreeTransferGraph(TreeNode* root) {
if (root == nullptr)return;
if (root->left != nullptr) {
TreeTransferGraph(root->left);
unmp[root].push_back(root->left);
unmp[root->left].push_back(root);
}
if (root->right != nullptr) {
TreeTransferGraph(root->right);
unmp[root].push_back(root->right);
unmp[root->right].push_back(root);
}
}
void dfs(TreeNode* node,TreeNode* root,int cnt,int k) {
if (cnt == k) {
vec.push_back(node->val);
return;
}
for (auto& child : unmp[node]) {
if (child == root)continue;
dfs(child,node, cnt + 1, k);
}
}
};