fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. struct TreeNode{
  5. int val;
  6. TreeNode* right;
  7. TreeNode* left;
  8.  
  9. TreeNode(int val) : left(nullptr),right(nullptr),val(val){};
  10. };
  11. TreeNode* lca(TreeNode* root,TreeNode* p,TreeNode* q){
  12. if(root == nullptr)return nullptr;
  13. if(p == root || q == root)return root;
  14.  
  15. TreeNode* left = lca(root->left,p,q);
  16. TreeNode* right = lca(root->right,p,q);
  17. if(left != nullptr && right != nullptr) {
  18. return root;
  19. }
  20. return left == nullptr?right:left;
  21. }
  22.  
  23.  
  24. TreeNode* buildTree(){
  25. int x;
  26. cin>>x;
  27. if(x==-1)return nullptr;
  28.  
  29. TreeNode* root = new TreeNode(x);
  30.  
  31. queue<TreeNode*>q;
  32.  
  33. q.push(root);
  34.  
  35. while(!q.empty()){
  36. auto u = q.front();q.pop();
  37.  
  38. if(cin>>x && x!=-1){
  39. u->left = new TreeNode(x);
  40. q.push(u->left);
  41. }
  42.  
  43. if(cin>>x && x!=-1){
  44. u->right = new TreeNode(x);
  45. q.push(u->right);
  46. }
  47. }
  48. return root;
  49. }
  50. TreeNode* find(TreeNode* root,int val){
  51. if(!root)return nullptr;
  52. if(root->val == val)return root;
  53.  
  54. TreeNode* left = find(root->left,val);
  55.  
  56. if(left)return left;
  57. return find(root->right,val);
  58. }
  59. int main() {
  60. TreeNode* root = buildTree();
  61. int val1,val2; cin>>val1 >>val2;
  62. TreeNode* p = find(root,val1);
  63. TreeNode* q = find(root,val2);
  64.  
  65. TreeNode* res = lca(root,p,q);
  66. if(res) {
  67. cout << res->val << endl;
  68. } else {
  69. cout << "Error: Could not find the nodes. Check your input!" << endl;
  70. }
  71.  
  72. return 0;
  73. }
Success #stdin #stdout 0.01s 5320KB
stdin
1 2 3 4 5 -1 -1 -1 -1 -1 -1 4 5
stdout
2