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. STM32 ~ CH340在STM32实现一键下载电路

    在做基于STM32的多功能MP3播放器的课题时,在程序下载这部分时借鉴了正点原子开发板上的一键下载电路,采用CH340G这款芯片设计. 在画PCB初期原理图部分,对采用CH340G设计的一键下载电路不 ...

  2. UI控件之UINavigationController

    ViewController1 *vc1=[[ViewController1 alloc]init]; UINavigationController *nav1=[[UINavigationContr ...

  3. git操作整理

    昨天手残 然后在GitHub for windows 上点了revert 然后就给重置了 更手残的是又给同步了 .  但是 GitHub 会保留之前的版本 . 只要删掉本次修改就可. 解决方案:  g ...

  4. DataTable Group By或运算 Linq Aggregate的使用

    class Program { static void Main(string[] args) { DataTable dt = new DataTable(); dt.Columns.Add(&qu ...

  5. 学会Retrofit+OkHttp+RxAndroid三剑客的使用,让自己紧跟Android潮流的步伐

    http://blog.csdn.net/iamzgx/article/details/51607387 概括 在上一篇博客android网络框架OkHttp之get请求(源码初识) 讲解了OkHtt ...

  6. ES6 随记(3.1)-- 字符串的拓展

    上一章请见: 1. ES6 随记(1)-- let 与 const 2. ES6 随记(2)-- 解构赋值 4. 拓展 a. 字符串的拓展 有些字符需要 4 个字节储存,比如 \uD83D\uDE80 ...

  7. 【Head First Servlets and JSP】笔记13:session & cookie

    session的接口 杀死会话 cookie的性质 cookie的接口 再总结——cookie.session.JSESSIONID的前世今生 简单的定制cookie示例 1.session的接口,配 ...

  8. systemverilog新增的always_comb,always_ff,和always_latch语句

    在Verilog中,设计组合逻辑和时序逻辑时,都要用到always: always @(*) //组合逻辑 if(a > b) out = 1; else out = 0; always @(p ...

  9. 生信概念之global alignment VS local alignment

  10. MySQL-LRU_List Free_List Flush_List

    关于 LRU_List ,Free_List,Flush_List的介绍:   LRU算法:(Latest Recent Used)最近最少使用      数据库的缓冲池通过LRU算法来进行管理.   ...