Skip to content

Latest commit

 

History

History
54 lines (43 loc) · 1.34 KB

File metadata and controls

54 lines (43 loc) · 1.34 KB
unordered_map<int,vector<int>> graph;
    int amountOfTime(TreeNode* root, int start) {
        constructGraph(root);

        queue<int>q;
        q.push(start);
        int ans=-1;

        unordered_set<int>visited;   //set for storing the visited nodes

        while(!q.empty())
        {
            ans++;

            for(int i=q.size();i>0;i--)
            {
                int curNode=q.front();
                visited.insert(curNode);
                q.pop();

                for(auto con: graph[curNode])
                {
                    if(visited.count(con)==0)       //con is not viisted yet
                        q.push(con);
                }
            }
            
        }
        return ans;
    }

    void constructGraph(TreeNode* root)
    {
        if(!root) return;

        if(root->left)
        {
            graph[root->val].push_back(root->left->val);
            graph[root->left->val].push_back(root->val);
        }

        if(root->right)
        {
            graph[root->val].push_back(root->right->val);
            graph[root->right->val].push_back(root->val);
        }

        constructGraph(root->left);
        constructGraph(root->right);
    }