fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. struct TreeNode{
  4. int val;
  5. vector<TreeNode*>children;
  6. TreeNode(int val):children({}),val(val){};
  7. };
  8. TreeNode* find(TreeNode* root,int d){
  9. if(root == nullptr)return nullptr;
  10. if(root->val==d){
  11. return root;
  12. }
  13.  
  14. for(auto &child:root->children){
  15. TreeNode* res = find(child,d);
  16. if (res != nullptr) return res;
  17. }
  18.  
  19. return nullptr;
  20. }
  21. vector<TreeNode*>nodeToRootPath(TreeNode* root,int d){
  22. if(root == nullptr)return {};
  23. if(root->val == d)return {root};
  24.  
  25.  
  26.  
  27. for(auto&child : root->children){
  28. vector<TreeNode*>childrenAns = nodeToRootPath(child,d);
  29. if(childrenAns.size()>0){
  30. childrenAns.push_back(root);
  31. return childrenAns;
  32. }
  33. }
  34. return {};
  35. }
  36. int LCA(TreeNode* p,TreeNode* q,TreeNode*root ){
  37.  
  38. vector<TreeNode*>path1=nodeToRootPath(root,p->val);
  39. vector<TreeNode*>path2=nodeToRootPath(root,q->val);
  40. int i = path1.size()-1;
  41. int j = path2.size()-1;
  42. while(i>=0&&j>=0&&path1[i]->val==path2[j]->val){
  43.  
  44. i--;
  45. j--;
  46. }
  47.  
  48. return path2[j+1]->val;
  49. }
  50. TreeNode* construct(vector<int>&arr){
  51. if(arr.empty()||arr[0]==-1)return nullptr;
  52. TreeNode* root = new TreeNode(arr[0]);
  53. stack<TreeNode*>st;
  54. st.push(root);
  55.  
  56. for(int i = 1;i<arr.size();i++){
  57. auto u = st.top();
  58. if(arr[i]==-1){
  59. st.pop();
  60. }else{
  61. TreeNode* newNode = new TreeNode(arr[i]);
  62. u->children.push_back(newNode);
  63. st.push(newNode);
  64. }
  65. }
  66. return root;
  67. }
  68. int main() {
  69. vector<int>arr = {1,2,4,-1,5,-1,-1,3,6,-1,7,-1,-1,-1};
  70. TreeNode* root = construct(arr);
  71. int d = 8;
  72.  
  73. TreeNode* p = new TreeNode(4);
  74. TreeNode* q = new TreeNode(5);
  75.  
  76. cout<<"LCA : "<<LCA(p,q,root)<<endl;
  77. cout<<endl;
  78. return 0;
  79. }
Success #stdin #stdout 0s 544KB
stdin
Standard input is empty
stdout
LCA : 2