Advertisement
tanchukw

1

Jul 29th, 2015
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.51 KB | None | 0 0
  1. https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
  2.  
  3. class Solution {
  4. public:
  5.     TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
  6.     {
  7.         if (root == NULL || p == NULL || q == NULL)
  8.             return NULL;
  9.         while ((root != NULL) && (root != p) && (root != q) && ((root->val > p->val && root->val > q->val) || (root->val < p->val && root->val < q->val)))
  10.         {
  11.             if (root->val > p->val)
  12.                 root = root->left;
  13.             else
  14.                 root = root->right;
  15.         }
  16.         return root;
  17.     }
  18. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement