Lowest Common Ancestor of a Binary Search Tree

Given a binary search tree (BST), find the lowest common ancestor (LCA) 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).”

Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5]
在这里插入图片描述
找搜索二叉树最近公共祖先与找二叉树最近公共祖先很像,但搜索二叉树特征更明显,我们可以利用该特征加速寻找。具体来说,当要找的两个节点分别位于root两侧,那说明root即为分裂点。当要找的p,q都大于或者小于root,那说明要去root的子树去找。而去子树找p,q又可用同样方式递归解决。

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

再聊聊普通二叉树如何找最近公共祖先。
在这里插入图片描述
假设找6,4的最近公共祖先,从root开始找,root又分别让左右子树去找,root负责汇总左右子树找的结果。左右子树依然会递归下去,那终止条件就是遇到空节点了或者找到某个要找的节点,那么就返回。返回后根节点开始汇总两个子树的结果,如果两颗子树都找到了,说明该root节点就是最近公共节点;若果左右子树有一棵树找到了,那么返回找到的节点。先自上而下找,回去的时候再层层往回传找的结果就可以找到要找的最近公共子节点。

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        return helper(root,p,q);
    }
    
    TreeNode* helper(TreeNode* root,TreeNode* p,TreeNode* q)
    {
        if(!root) return root;
        if (root->val==p->val||root->val==q->val) return root;
        TreeNode *left,*right;
        left = helper(root->left,p,q);
        right = helper(root->right,p,q);
        if (left&&right) return root;
        return left?left:right;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值