https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

1. Use recursion:

  1. //40 ms 23.5 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  14. if(!root) return NULL;
  15. if(p->val > root->val && q->val > root->val)
  16. return lowestCommonAncestor(root->right, p, q);
  17. else if(p->val < root->val && q->val < root->val)
  18. return lowestCommonAncestor(root->left, p, q);
  19. else
  20. return root;
  21. }
  22. };

2. Use iteration:

  1. //44 ms 23.3 MB
  2. /**
  3. * Definition for a binary tree node.
  4. * struct TreeNode {
  5. * int val;
  6. * TreeNode *left;
  7. * TreeNode *right;
  8. * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
  14. if(!root) return NULL;
  15. while(root){
  16. if(p->val > root->val && q->val > root->val)
  17. root = root->right;
  18. else if(p->val < root->val && q->val < root->val)
  19. root = root->left;
  20. else
  21. return root;
  22. }
  23. return NULL;
  24. }
  25. };