【LeetCode 235_二叉搜索树】Lowest Common Ancestor of a Binary Search Tree

解法一:递归

 1 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
 2 {
 3     if (root == NULL || p == NULL || q == NULL)
 4         return NULL;
 5 
 6     if (root->val > p->val && root->val > q->val)
 7         return lowestCommonAncestor(root->left, p, q);
 8     else if (root->val < p->val && root->val < q->val)
 9         return lowestCommonAncestor(root->right, p, q);
10     return root;
11 }

解法二:迭代

 1 TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)
 2 {
 3     if (root == NULL || p == NULL || q == NULL)
 4         return NULL;
 5 
 6     while (true) {
 7         if (root->val < p->val && root->val < q->val)
 8             root = root->right;
 9         else if (root->val > p->val && root->val > q->val)
10             root = root->left;
11         else
12             break;
13     }
14     return root;
15 }

 

相关文章:

  • 2021-06-16
  • 2021-06-22
  • 2021-08-24
  • 2021-07-01
  • 2021-08-24
  • 2022-01-10
猜你喜欢
  • 2021-06-12
  • 2021-12-17
  • 2022-01-13
  • 2021-07-30
  • 2021-11-15
  • 2021-09-17
相关资源
相似解决方案