Advertisement
nikunjsoni

236

May 8th, 2021
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.12 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  8.  * };
  9.  */
  10. class Solution {
  11. public:
  12.     TreeNode* lca;
  13.     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  14.         lca = NULL;
  15.         bool found = false;
  16.         dfs(root, p, q, found);
  17.         return lca;
  18.     }
  19.    
  20.     pair<bool, bool> dfs(TreeNode* root, TreeNode*p, TreeNode* q, bool &found){
  21.         if(found) return {true, true};
  22.         if(!root) return {false, false};
  23.        
  24.         auto left = dfs(root->left, p, q, found);
  25.         auto right = dfs(root->right, p, q, found);
  26.        
  27.         pair<bool, bool> seen;
  28.         seen.first = (left.first || right.first);
  29.         seen.second = (left.second || right.second);
  30.        
  31.         if(root->val == p->val) seen.first = true;
  32.         if(root->val == q->val) seen.second = true;
  33.        
  34.         if(seen.first && seen.second && !found){
  35.             found = true;
  36.             lca = root;
  37.         }
  38.         return seen;
  39.     }
  40.    
  41. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement