Advertisement
SalmaYasser

Untitled

Oct 23rd, 2019
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  13.                 if (root == nullptr)
  14.             return root;
  15.         if (root == p || root == q)
  16.             return root;
  17.         TreeNode* l = lowestCommonAncestor (root -> left , p , q);
  18.         TreeNode* r = lowestCommonAncestor ( root -> right , p , q);
  19.        
  20.         if (l && r)
  21.             return root;
  22.         if ( l && !r)
  23.             return l;
  24.         else return r;
  25.        
  26.     }
  27. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement