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.

求最近的公共祖先,很显然,对于二叉搜索树来说,当两个节点的值都比root小的时候,lca应该在root左节点这一侧, 都比root值大的时候都在右节点这一侧,否则root

就是lca,代码见下所示:

 /**
* 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(max(p->val, q->val) < root->val)
lowestCommonAncestor(root->left, p, q);
else if(min(p->val, q->val) > root->val)
lowestCommonAncestor(root->right,p ,q);
else
return root;
}
};

而对于非二叉搜索树来说,做法一般是先分别查找到到P以及Q的路线,然后对比路线,找出LCA,代码如下:

 class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root == NULL || p == NULL || q == NULL)
return NULL;
vector<TreeNode *>pathP;
vector<TreeNode *>pathQ;
pathP.push_back(root);
pathQ.push_back(root);
getPath(root, p, pathP);
getPath(root, q, pathQ);
TreeNode * lca = NULL;
for(int i = ; i < pathP.size() && i < pathQ.size(); ++i){
if(pathP[i] == pathQ[i])  //检查lca
lca = pathP[i];
else break;
}
return lca;
} bool getPath(TreeNode * root, TreeNode * target, vector<TreeNode * > & path)
{
if(root == target)
return true;
if(root->left){
path.push_back(root->left);
if(getPath(root->left, target, path)) return true;
path.pop_back();
}
if(root->right){
path.push_back(root->right);
if(getPath(root->right, target, path)) return true;
path.pop_back();
}
return false;
}
};

java版本的如下所示:

 public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(Math.max(p.val, q.val) < root.val){
return lowestCommonAncestor(root.left, p, q);
}else if(Math.min(p.val, q.val) > root.val){
return lowestCommonAncestor(root.right, p, q);
}else{
return root;
}
}
}

LeetCode OJ:Lowest Common Ancestor of a Binary Search Tree(最浅的公共祖先)的更多相关文章

  1. LeetCode Lowest Common Ancestor of a Binary Search Tree (LCA最近公共祖先)

    题意: 给一棵二叉排序树,找p和q的LCA. 思路: 给的是BST(无相同节点),那么每个节点肯定大于左子树中的最大,小于右子树种的最小.根据这个特性,找LCA就简单多了. 分三种情况: (1)p和q ...

  2. leetcode 235. Lowest Common Ancestor of a Binary Search Tree 236. Lowest Common Ancestor of a Binary Tree

    https://www.cnblogs.com/grandyang/p/4641968.html http://www.cnblogs.com/grandyang/p/4640572.html 利用二 ...

  3. [LeetCode] 235. 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 BS ...

  4. [LeetCode] 235. 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 BS ...

  5. LeetCode 235. 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 BS ...

  6. leetcode 235. 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 BS ...

  7. (easy)LeetCode 235.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 BS ...

  8. leetcode: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 BS ...

  9. Java [Leetcode 235]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 ...

  10. LeetCode (236):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 BS ...

随机推荐

  1. Python基础-生成器和迭代器

    生成器都是迭代器,迭代器不一定是生成器 def fansik(max): n, before, after = 0, 0, 1 while n < max: print(before) befo ...

  2. 剑指offer 面试21题

    面试21题: 题目:调整数组的顺序使奇数位于偶数前面 题一:输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有奇数位于数组的前半部分,所有偶数位于数组的后半部分. 解题思路:使用两个指针 ...

  3. 分布式计算开源框架Hadoop入门实践(二)

    其实参看Hadoop官方文档已经能够很容易配置分布式框架运行环境了,不过这里既然写了就再多写一点,同时有一些细节需要注意的也说明一下,其实也就是这些细节会让人摸索半天.Hadoop可以单机跑,也可以配 ...

  4. Android Http Get Post

    public class MyHttpUrlCon { public static String settionId = ""; ;// public ReturnData doG ...

  5. ETL应用:使用shell实现文件级校验的方法

    BI应用中,对接口规范性约束很重要,接口文件提供需要配套提供该文件的校验文件,校验文件格式如下: 序号 信息内容 数据类型及长度 说明 1 接口数据文件名称 CHAR(50) 2 文件的大小(字节数) ...

  6. 20145230《java学习笔记》第九周学习总结

    20145230 <Java程序设计>第9周学习总结 教材学习内容 JDBC JDBC简介 JDBC是用于执行SQL的解决方案,开发人员使用JDBC的标准接口,数据库厂商则对接口进行操作, ...

  7. Python中的条件选择和循环语句

    一.条件选择语句 Python中条件选择语句的关键字为:if .elif .else这三个.其基本形式如下: if condition: block elif condition: block ... ...

  8. [Python] 弗洛伊德(Floyd)算法求图的直径并记录路径

    相关概念 对于一个图G=(V, E),求图中两点u, v间最短路径长度,称为图的最短路径问题.最短路径中最长的称为图的直径. 其中,求图中确定的某两点的最短路径算法,称为单源最短路径算法.求图中任意两 ...

  9. eclipse修改端口启动多个tomcat

    参考:https://blog.csdn.net/zl544434558/article/details/47857343 在一个eclipse启动多个tomcat,修改tomcat的端口是不可以的, ...

  10. thinkphp判断更新是否成功

    如何判断一个更新操作是否成功 $Model = D('Blog'); $data['id'] = 10; $data['name'] = 'update name'; $result = $Model ...