One pass dfs
Intuition\npreprocess to pass the time and space limits\n# Approach\n hint: store nodes in given level, heights and depths of every node\n\n# Complexity\n- Time
# Intuition\npreprocess to pass the time and space limits\n# Approach\n hint: store nodes in given level, heights and depths of every node\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```cpp []\n/**\n * Definition for a binary tree node.\n * struct TreeNode {\n *     int val;\n *     TreeNode *left;\n *     TreeNode *right;\n *     TreeNode() : val(0), left(nullptr), right(nullptr) {}\n *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}\n *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}\n * };\n */\nclass Solution {\npublic:\n    int ht[100001];\n    int depth[100001];\n    int lvl[100001][2];\n    unordered_map<int,vector<int>>mp;\n    int dfs(TreeNode* root,int d){\n        if(!root) return 0;\n        depth[root->val] = d;\n        mp[d].push_back(root->val);\n        return ht[root->val] = 1+max(dfs(root->left,d+1), dfs(root->right,d+1));\n    }\n\n    vector<int> treeQueries(TreeNode* root, vector<int>& queries) {\n        int q = queries.size();\n        mp.clear();\n        dfs(root,0);\n        for(auto [l,k]:mp){\n            int maxi = 0, mini = 0;\n            for(auto v:k){\n                int temp = (ht[v]+depth[v]-1); \n                if(maxi<=temp){\n                    mini = maxi;\n                    maxi = temp;\n                }\n                else if(mini<temp){\n                    mini = temp;\n                }\n            }\n            lvl[l][0] = maxi;\n            lvl[l][1] = mini;\n        }\n        vector<int>ans;\n        for(int i=0;i<q;i++){\n            int node = queries[i];\n            if(mp[depth[node]].size()==1) ans.push_back(depth[node]-1);\n            else{\n                if(lvl[depth[node]][0]==depth[node]+ht[node]-1) \n                    ans.push_back(lvl[depth[node]][1]);\n                else ans.push_back(lvl[depth[node]][0]);\n            }\n        }\n        return ans;\n    }\n};\n```
['C++']