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. mysql启动报错“NET HELPMSG 3534“的解决办法

    原因: mysql安装步骤错误,从mysql5.7.6开始,mysql需要这样安装: mysqld --initialize-insecure或者mysqld --initialize mysqld ...

  2. Python2 socket 多线程并发 TCPServer Demo

    #coding=utf-8 import socket import threading,getopt,sys,string opts, args = getopt.getopt(sys.argv[1 ...

  3. mysql用户管理(新增用户及权限管理)

    一.登录: # mysql  –u  root  –p  回车输入密码 退出: #exit; 二.修改密码: 格式:mysqladmin  –u 用户名 –p旧密码  password  新密码 # ...

  4. github资源下载速度慢的解决办法

    xx-net:https://github.com/XX-net/XX-Net

  5. Python编程-继承和接口

    一.继承 1.什么是继承 继承是一种创建新类的方式,在python中,新建的类可以继承一个或多个父类,父类又可称为基类或超类,新建的类称为派生类或子类. 继承的好处: 可以使用现有类的所有功能,并在无 ...

  6. 跨平台移动开发 App-Framework DEMO 演示

    穿越到2015 回到->MarkFan的程序员客栈 App-Framework   DEMO 演示 点击APK包下载 点击Demo代码下载 官方网站 :http://app-framework- ...

  7. 默认连接电脑的模式为MTP【转】

    本文转载自:https://blog.csdn.net/tangzhihai0421/article/details/53487208 Android L后默认的usb连接模式为“仅充电”,而且不会随 ...

  8. JSP语法及内置对象

    JSP全名为Java Server Pages,中文名叫java服务器页面,其根本是一个简化的Servlet设计,它[1]  是由Sun Microsystems公司倡导.许多公司参与一起建立的一种动 ...

  9. Go 功能测试与性能测试

    1.功能测试 calcTriangle.go // 需要被测试的函数 func calcTriangle(a, b int) int { return int(math.Sqrt(float64(a* ...

  10. juniper常用命令(二)

    Juniper防火墙基本命令 常用查看命令 Get int查看接口配置信息 Get int ethx/x查看指定接口配置信息 Get mip查看映射ip关系 Get route查看路由表 Get po ...