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]
_______6______
/ \
___2__ ___8__
/ \ / \
0 _4 7 9
/ \
3 5
Example 1:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes2
and8
is6
.
Example 2:
Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes2
and4
is2
, since a node can be a descendant of itself
according to the LCA definition.
Note:
- All of the nodes' values will be unique.
- p and q are different and both values will exist in the BST.
求二叉搜索树(BST)的最近公共祖先(LCA)。最近公共祖先是指在一个树或者有向无环图中同时拥有v和w作为后代的最深的节点。
解法1:递归,
1. P, Q都比root小,则LCA在左树,我们继续在左树中寻找LCA
2. P, Q都比root大,则LCA在右树,我们继续在右树中寻找LCA
3. 其它情况,表示P,Q在root两边,或者二者其一是root,或者都是root,这些情况表示root就是LCA,直接返回root即可。
解法2: 迭代
判断标准同解法1,只是用迭代来实现。
Java:
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root.val > p.val && root.val > q.val) return lowestCommonAncestor(root.left, p, q);
if(root.val < p.val && root.val < q.val) return lowestCommonAncestor(root.right, p, q);
return root;
}
}
Java:
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
//发现目标节点则通过返回值标记该子树发现了某个目标结点
if(root == null || root == p || root == q) return root;
//查看左子树中是否有目标结点,没有为null
TreeNode left = lowestCommonAncestor(root.left, p, q);
//查看右子树是否有目标节点,没有为null
TreeNode right = lowestCommonAncestor(root.right, p, q);
//都不为空,说明做右子树都有目标结点,则公共祖先就是本身
if(left!=null&&right!=null) return root;
//如果发现了目标节点,则继续向上标记为该目标节点
return left == null ? right : left;
}
}
Python:
class Solution:
# @param {TreeNode} root
# @param {TreeNode} p
# @param {TreeNode} q
# @return {TreeNode}
def lowestCommonAncestor(self, root, p, q):
s, b = sorted([p.val, q.val])
while not s <= root.val <= b:
# Keep searching since root is outside of [s, b].
root = root.left if s <= root.val else root.right
# s <= root.val <= b.
return root
C++:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if (!root) return NULL;
if (root->val > max(p->val, q->val))
return lowestCommonAncestor(root->left, p, q);
else if (root->val < min(p->val, q->val))
return lowestCommonAncestor(root->right, p, q);
else return root;
}
};
C++:
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
while (true) {
if (root->val > max(p->val, q->val)) root = root->left;
else if (root->val < min(p->val, q->val)) root = root->right;
else break;
}
return root;
}
};
类似题目:
[LeetCode] 236. Lowest Common Ancestor of a Binary Tree 二叉树的最近公共祖先
All LeetCode Questions List 题目汇总
[LeetCode] 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先的更多相关文章
-
235 Lowest Common Ancestor of a Binary Search Tree 二叉搜索树的最近公共祖先
给定一棵二叉搜索树, 找到该树中两个指定节点的最近公共祖先. 详见:https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-s ...
-
[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 ...
-
[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 ...
-
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 利用二 ...
-
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 ...
-
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 ...
-
(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 ...
-
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 ...
-
Leetcode 235 Lowest Common Ancestor of a Binary Search Tree 二叉树
给定一个二叉搜索树的两个节点,找出他们的最近公共祖先,如, _______6______ / \ ___2__ ___8__ / \ / \ 0 4 7 9 / \ 3 5 2和8的最近公共祖先是6, ...
随机推荐
-
[知识点]Trie树和AC自动机
// 此博文为迁移而来,写于2015年5月27日,不代表本人现在的观点与看法.原始地址:http://blog.sina.com.cn/s/blog_6022c4720102w1s8.html 1.前 ...
-
程序自启动及后台持续运行的研究(voip和GPS方式)
1,voip方式 1)首先要修改应用的plist配置,添加下面的设置: Application does not run in background: NO Requ ...
-
unity, 用unity profiler进行真机profile,需要退出360
用unity profiler进行真机profile,需要退出360.
-
BackTrack5 (BT5)无线password破解教程之WPA/WPA2-PSK型无线password破解
昨天公布了BackTrack5 (BT5)无线weppassword破解教程之minidwep-gtk破解法一文,对BT5下破解wep无线password的简单方法做了介绍,今天奶牛为朋友们介绍下怎样 ...
-
对同一个项目下的多个数据库Context进行迁移Migrations
PM> Enable-Migrations -MigrationsDirectory "Migrations\ContextA" -ContextTypeName MyPro ...
-
CocoaPods ADD private Spec Repo
Private Pods CocoaPods is a great tool not only for adding open source code to your project, but als ...
-
HDU 3571 N-dimensional Sphere
高斯消元,今天数学死了无数次…… #include <cstdio> #include <cstring> #include <cmath> #include &l ...
-
jsScript中的一些操作方法
1.采用dom方式对script标签进行操作 var h = document.getElementsByTagName('HEAD').item(0); var s = document.creat ...
-
3.5 find() 判断是否存在某元素
vector 判断是否存在某元素: if(find(A.begin(), A.end(), A[i]) != A.end()){ // 若存在 A[i] // find() 返回一个指针 }
-
python 获取lazada菲律宾站地址库
import urllib3 import requests import ast import time # 因为lazada返回的数据是json类型,通过解码成字符串类型,为了方便数据操作,使用字 ...