O(N) solution
Intuition\n Describe your first thoughts on how to solve this problem. \npreprocess everything\n# Approach\n Describe your approach to solving the problem. \nsa
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\npreprocess everything\n# Approach\n<!-- Describe your approach to solving the problem. -->\nsave the height and depth of all nodes at every level\n# Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(N)\n<!-- Add your space complexity here, e.g. $$O(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 */\n\nclass Solution {\npublic:\n    unordered_map<int,vector<int>> mp;\n    unordered_map<int,int> mp_row;\n    unordered_map<int,int> mp_depth;\n    unordered_map<int,pair<int,int>> lvl;\n    void prep(){\n        for(int i=0;mp[i].size()!=0;i++){\n            lvl[i].first=0;\n            lvl[i].second=0;\n            for(int j:mp[i]){\n                if(lvl[i].first<=i+mp_depth[j]){\n                    lvl[i].second = lvl[i].first;\n                    lvl[i].first = i+mp_depth[j];\n                }else if(lvl[i].second<i+mp_depth[j])\n                    lvl[i].second = i+mp_depth[j];\n            }\n        }\n    }\n\n    int height(TreeNode* root, int level) {\n        if(!root) return 0;\n\n        mp_row[root->val] = level;\n        mp[level].push_back(root->val);\n\n        int l = height(root->left, level + 1);\n        int r = height(root->right, level + 1);\n        int curr = 1 + max(l, r);\n\n        mp_depth[root->val] = curr-1;\n\n        return curr;\n    }\n    vector<int> treeQueries(TreeNode* root, vector<int>& queries) {\n        int h=height(root,0);\n        prep();\n        vector<int> ans;\n        for(auto k:queries){\n            int row = mp_row[k];\n            if(mp[row].size()==1){\n                ans.push_back(row-1);\n                continue;\n            }else{\n                if(lvl[row].first==row+mp_depth[k]) ans.push_back(lvl[row].second);\n                else ans.push_back(lvl[row].first);\n            }\n        }\n        return ans;\n    }\n};\n```
['Array', 'Tree', 'Depth-First Search', 'Breadth-First Search', 'Binary Tree', 'C++']