From 406e79ed32020611e273d0914fc60ea17c2b9160 Mon Sep 17 00:00:00 2001 From: chenximing <243744327@qq.com> Date: Tue, 6 Jun 2023 23:03:48 +0800 Subject: [PATCH] leetcode --- ...25\351\242\230\346\200\273\347\273\223.md" | 62 +++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204\344\270\216\347\256\227\346\263\225/\347\256\227\346\263\225\351\242\230\346\200\273\347\273\223.md" "b/\346\225\260\346\215\256\347\273\223\346\236\204\344\270\216\347\256\227\346\263\225/\347\256\227\346\263\225\351\242\230\346\200\273\347\273\223.md" index a9ca3a6..f3065cf 100644 --- "a/\346\225\260\346\215\256\347\273\223\346\236\204\344\270\216\347\256\227\346\263\225/\347\256\227\346\263\225\351\242\230\346\200\273\347\273\223.md" +++ "b/\346\225\260\346\215\256\347\273\223\346\236\204\344\270\216\347\256\227\346\263\225/\347\256\227\346\263\225\351\242\230\346\200\273\347\273\223.md" @@ -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 distanceK(TreeNode* root, TreeNode* target, int k) { + unordered_map > m; + buildGraph(root, m); + + deque 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 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 > &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); + } + } +}; +``` +