1.題目
給定一個(gè)二叉搜索樹, 找到該樹中兩個(gè)指定節(jié)點(diǎn)的最近公共祖先。
百度百科中最近公共祖先的定義為:“對(duì)于有根樹 T 的兩個(gè)結(jié)點(diǎn) p、q,最近公共祖先表示為一個(gè)結(jié)點(diǎn) x,滿足 x 是 p、q 的祖先且 x 的深度盡可能大(一個(gè)節(jié)點(diǎn)也可以是它自己的祖先)。”
例如,給定如下二叉搜索樹: root = [6,2,8,0,4,7,9,null,null,3,5]
示例 1:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
輸出: 6
解釋: 節(jié)點(diǎn) 2 和節(jié)點(diǎn) 8 的最近公共祖先是 6。
示例 2:
輸入: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
輸出: 2
解釋: 節(jié)點(diǎn) 2 和節(jié)點(diǎn) 4 的最近公共祖先是 2, 因?yàn)楦鶕?jù)定義最近公共祖先節(jié)點(diǎn)可以為節(jié)點(diǎn)本身。
說明:
所有節(jié)點(diǎn)的值都是唯一的。
p、q 為不同節(jié)點(diǎn)且均存在于給定的二叉搜索樹中。
來源:力扣(LeetCode)
鏈接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-search-tree
2.思路
(1)遞歸
(2)一次遍歷文章來源:http://www.zghlxwxcb.cn/news/detail-409516.html
相關(guān)題目:
LeetCode_二叉樹_中等_236.二叉樹的最近公共祖先文章來源地址http://www.zghlxwxcb.cn/news/detail-409516.html
3.代碼實(shí)現(xiàn)(Java)
//思路1————遞歸
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) {
return null;
}
if (root == p || root == q) {
return root;
}
//在當(dāng)前根節(jié)點(diǎn) root 的左右子樹中去尋找 p、q 的最近公共祖先
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
// p、q 分別在左右子樹中
if (left != null && right != null) {
return root;
}
if (left == null && right == null) {
return null;
}
return left == null ? right : left;
}
}
//思路2————一次遍歷
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode ancerstor = root;
//利用二叉搜索樹的性質(zhì)進(jìn)行一次遍歷
while (true) {
if (p.val < ancerstor.val && q.val < ancerstor.val) {
// p、q 在 ancerstor 左側(cè)
ancerstor = ancerstor.left;
} else if (p.val > ancerstor.val && q.val > ancerstor.val) {
// p、q 在 ancerstor 右側(cè)
ancerstor = ancerstor.right;
} else {
// p、q 分別在 ancerstor 兩側(cè)
break;
}
}
return ancerstor;
}
}
到了這里,關(guān)于LeetCode_二叉搜索樹_中等_236.二叉搜索樹的最近公共祖先的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!