problemscpp
A collection of my answers to algorithm problems in c++.
静态 Public 成员函数 | 所有成员列表
leetcode::all_nodes_distance_k_in_binary_tree::Solution类 参考

#include <leetcode.h>

静态 Public 成员函数

static vector< int > distanceK (TreeNode *root, TreeNode *target, int k)
 

详细描述

在文件 leetcode.h2902 行定义.

成员函数说明

◆ distanceK()

vector< int > leetcode::all_nodes_distance_k_in_binary_tree::Solution::distanceK ( TreeNode root,
TreeNode target,
int  k 
)
static

在文件 leetcode.cpp8010 行定义.

8010 {
8011 if(k == 0) {
8012 return {target->val};
8013 }
8014 unordered_map<TreeNode *, Node *> um;
8015 vector<int> ans;
8016 queue<TreeNode *> q1;
8017 q1.push(root);
8018 um[root] = new Node(root->val);
8019 while(!q1.empty()) {
8020 TreeNode *tn = q1.front();
8021 q1.pop();
8022 if(tn->left != nullptr) {
8023 q1.push(tn->left);
8024 um[tn->left] = new Node(tn->left->val);
8025 um[tn->left]->siblings.insert(um[tn]);
8026 um[tn]->siblings.insert(um[tn->left]);
8027 }
8028 if(tn->right != nullptr) {
8029 q1.push(tn->right);
8030 um[tn->right] = new Node(tn->right->val);
8031 um[tn->right]->siblings.insert(um[tn]);
8032 um[tn]->siblings.insert(um[tn->right]);
8033 }
8034 }
8035 Node *node = um[target];
8036 unordered_set<Node *> vis;
8037 queue<pair<int, Node *>> q2;
8038 q2.push({0, node});
8039 while(!q2.empty()) {
8040 auto [d, nd] = q2.front();
8041 q2.pop();
8042 vis.insert(nd);
8043 for(auto *sibling: nd->siblings) {
8044 if(!vis.contains(sibling)) {
8045 vis.insert(sibling);
8046 if(d + 1 == k) {
8047 ans.emplace_back(sibling->val);
8048 } else {
8049 q2.push({d + 1, sibling});
8050 }
8051 }
8052 }
8053 }
8054 return ans;
8055 }
vector< int > root
Definition: acwing408.cpp:349

引用了 leetcode::TreeNode::left, leetcode::TreeNode::right, acwing::acwing836_408::root , 以及 leetcode::TreeNode::val.


该类的文档由以下文件生成: