Leetcoe 863. All Nodes Distance K in Binary Tree

dfs和bfs版本,不过我是先转化成图的,以为效率会低很多,没想到还打败了90多的人

/**
 * 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:
    unordered_map> g;
    vector distanceK(TreeNode* root, TreeNode* target, int K) {
        vector v;
        if(!root)
            return v;
        buildgraph(NULL,root);
        unordered_set vis;
        vis.insert(target);
        // dfs(target,0,K,v,vis);
        queue q;
        q.push(target);
        int k= 0;
        while(!q.empty() && k<=K){
            int size = q.size();
            while(size--){
                TreeNode* node = q.front();
                q.pop();
                if(k == K)
                    v.push_back(node->val);
                for(auto it=g[node].begin();it != g[node].end();it++){
                    if(vis.count(*it)) continue;
                    q.push(*it);
                    vis.insert(*it);
                }
            }
            k++;
        }
        return v;
    }
    void buildgraph(TreeNode* parent,TreeNode* child){
        if(parent){
            g[parent].push_back(child);
            g[child].push_back(parent);
        }
        if(child->left) buildgraph(child,child->left);
        if(child->right) buildgraph(child,child->right);
    }
    void dfs(TreeNode* begin,int k,int K,vector &v,unordered_set &vis){
        if(!begin) return;
        if(k == K){
            v.push_back(begin->val);
            return;
        }
        if(k>K) return;
        for(auto it=g[begin].begin();it != g[begin].end();it++){
            if(vis.count(*it))
                continue;
            vis.insert(*it);
            dfs(*it,k+1,K,v,vis);
        }
    }
};

 

你可能感兴趣的:(leetcode)