235. Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) node of two given nodes in the BST.

According to the definition of LCA on Wikipedia: "The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself)."

Example 1:

复制代码
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

复制代码
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Example 3:

复制代码
Input: root = [2,1], p = 2, q = 1
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [2, 105].
  • -109 <= Node.val <= 109
  • All Node.val are unique.
  • p != q
  • p and q will exist in the BST.

递归法:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        if(root->val>p->val && root->val>q->val){
            return lowestCommonAncestor(root->left,p,q);
        }
        else if(root->val<p->val && root->val<q->val){
            return lowestCommonAncestor(root->right,p,q);
        }
        else return root;
    }
};

注意:

第一步,如果root->val比pq都要大就递归左子树,反之递归右子树

第二步,如果不是上面两种(root就是最近公共祖先)就返回root

迭代:

class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        while(root){
            if(root->val>p->val && root->val>q->val)root=root->left;
            else if(root->val<p->val && root->val<q->val)root=root->right;
            else return root;
        }
        return NULL;
    }
};

注意:

不要忘记最后一行的return NULL,又是被这么简短的迭代感动哭的一天

相关推荐
星空露珠7 分钟前
迷你世界脚本文字板接口:Graphics
数据结构·游戏·lua
eason_fan7 分钟前
前端手撕代码(bigo)
算法·面试
302wanger20 分钟前
ARTS-算法-长度最小的子数组
算法
Maple_land1 小时前
C++入门——命名空间
c++
lizz311 小时前
机器学习中的线性代数:奇异值分解 SVD
线性代数·算法·机器学习
_星辰大海乀1 小时前
LinkedList 双向链表
java·数据结构·链表·list·idea
MSTcheng.1 小时前
【C语言】动态内存管理
c语言·开发语言·算法
不去幼儿园1 小时前
【启发式算法】Dijkstra算法详细介绍(Python)
人工智能·python·算法·机器学习·启发式算法·图搜索算法
serve the people1 小时前
神经网络中梯度计算求和公式求导问题
神经网络·算法·机器学习
桃酥4031 小时前
20、移动语义有什么作用,原理是什么【中高频】
c++