240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 21 | Leetcode 863. All Nodes Distance K in Binary Tree

题解

Medium

BFS

Tree 是一种特殊的 Graph,节点之间只有一个方向。而这里有从 Target 节点向各个方向,包括父节点方向,遍历的需求。所以利用 Hashmap 先转化成一个无向图。

/**
 * 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) {
        vector<int> ret;
        
        // convert to bi-directional graph
        unordered_map<TreeNode*, vector<TreeNode*>> graph;
        unordered_set<TreeNode*> visited; // avoid cycle traversal
        
        queue<TreeNode*> q;
        q.push(root);
        
        while(!q.empty()) {
            auto t = q.front();
            q.pop();
            
            if(t->left) {
                graph[t].push_back(t->left);
                graph[t->left].push_back(t);
                q.push(t->left);
            }
            if(t->right) {
                graph[t].push_back(t->right);
                graph[t->right].push_back(t);
                q.push(t->right);
            }
        }
        
        // start from target
        q.push(target);
        
        while(!q.empty() && K >= 0) {
            int sz = q.size();
            for(int i = 0; i < sz; i++) {
                auto t = q.front();
                q.pop();
                
                visited.insert(t);
                
                if(K == 0) {
                    ret.push_back(t->val);
                }
                
                for(auto node : graph[t]) {
                    if(!visited.count(node)) q.push(node);
                }
            }
            K--;
        }
        
        return ret;
    }
};
posted @ 2020-10-09 07:30  CasperWin  阅读(129)  评论(0编辑  收藏  举报