Beats 100% || Easy understandable c++
\n\n# Approach\n\nDo a preorder traversal of the whole tree and then find all the Tree Nodes with highest depth, and then by using lowest common ancestor of any
![image.png](https://assets.leetcode.com/users/images/f3233443-76ef-48aa-b307-c1434a3bc91e_1720204246.948445.png)\n\n# Approach\n\nDo a preorder traversal of the whole tree and then find all the Tree Nodes with highest depth, and then by using lowest common ancestor of any two nodes find the lowest common ancestor of all the nodes with highest depth \n\n\n# Code\n```\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    TreeNode* lca(TreeNode* root, TreeNode* p, TreeNode* q) {\n        if(root== NULL) return root;\n        if(root==p || root == q) return root;\n        TreeNode* l1 = lca(root->left,p,q);\n        TreeNode* l2 = lca(root->right,p,q);\n        if(l1==NULL) return l2;\n        if(l2==NULL) return l1;  \n        if( (l1 ==p && l2 ==q) ||(l1 ==q && l2 ==p) ) return root;\n        return NULL;\n    }\n    void preord(TreeNode* root,vector<pair<TreeNode*,int>>&v,int d){\n        if(root == NULL) return;\n        v.push_back({root,d});\n        preord(root->left,v,d+1);\n        preord(root->right,v,d+1);\n    }\n    TreeNode* subtreeWithAllDeepest(TreeNode* root) {\n        vector<pair<TreeNode*,int>>v;\n        preord(root,v,0);\n        vector<TreeNode*>deeps;\n        int maxdeep = 0;\n        for(int i=0;i<v.size();i++){\n            maxdeep = max(maxdeep,v[i].second);\n        }\n        for(int i=0;i<v.size();i++){\n            if(v[i].second == maxdeep){\n                deeps.push_back(v[i].first);\n            }\n        }\n        if(deeps.size() == 1) return deeps[0];\n        TreeNode* ans ;\n        ans = lca(root,deeps[0],deeps[1]);\n        for(int i=2;i<deeps.size();i++){\n            ans = lca(root,ans,deeps[i]);\n        }\n        return ans;\n    }\n};\n```
['Tree', 'Depth-First Search', 'C++']