LeetCode Everyday -- 253

进入正题之前先扯些废话。以下可以跳过。
现在大三了,马上就要毕业找工作了。暮然回首,发现这三年除了学了一些在外行人面前装逼的词汇外并没有学到什么太多东西。上课也是水水的求个及格,浑浑噩噩过了三年。在大学最后这一年里,希望能过重新学点东西,不至于荒废四年。
我们程序员外修语言内修算法。所以,我决定重新开始学习算法。在知乎上逛了一圈,决定从刷leetcode开始。
leetcode上题目分easy,medium,hard三个水平,每个题目会统计出ac率,所以,作为算法菜鸟,将easy的题目筛选出来,从ac最高的开始,进入算法的学习之路。

由于水平有限,难免出现差错,希望各位大神能过指正。


好了,废话说完了,进入正题。

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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”

        _______6______
       /              \
    ___2__          ___8__
   /      \        /      \
   0       4       7       9
         /  \
         3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

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

leetcode上支持多种语言提交,包括C,C++,java,python,js等,未来提高算法效率,我选择的是C/C++语言。从leetcode统计的数据来看,C,C++普遍比其他语言快。
解题思路:
题目的关键是BST,BST(二叉搜索树)学过数据结构的人都应该知道,它一个重要的特点就是树的左边<根节点<左边,所以,要找到两个节点的公共祖先,关键就是找到一个节点让两个节点分布在它的两侧。因为要找最近公共祖先,所以从根节点开始一层层往下找,找到的第一个节点即为最近根节点。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值