Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]
Posted Lnho
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]相关的知识,希望对你有一定的参考价值。
题目:
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).”
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.
翻译:
给定一个搜索二叉树,找到给定的2个节点的最小共同祖先(LCA)。
根据维基百科对LCA的定义,最小共同祖先是定义在树T中的一个最小节点,这个最小节点满足,树上的另外2个节点v和w都是它的子孙(这里我们允许一个是它自己的子孙)。
例如上图中的2和8的LCA是6,2和4的LCA是2。
分析:
这道题的思路是从根节点这个共同祖先的节点开始,根据搜索二叉树的性质,也就是任一节点的左子树的所有节点的值一定会比该节点的小,右子树一定会比该节点大,一步步找到最小的共同祖先。
而如果遍历到某一节点时,2棵子树的值既没有都比该节点小,也没有都比该节点大,只有2种可能:第一种可能是2棵子树的值,一个比该节点大,一个比该节点小;另外一种可能其中至少有一个子树的值等于该节点。不管是哪种可能,这个时候最小共同祖先都为该节点。
代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
TreeNode LCA=root;
while(true){
if(p.val<LCA.val&&q.val<LCA.val){
LCA=LCA.left;
}else if(p.val>LCA.val&&q.val>LCA.val){
LCA=LCA.right;
}else{
break;
}
}
return LCA;
}
}
以上是关于Leet Code OJ 235. Lowest Common Ancestor of a Binary Search Tree [Difficulty: Easy]的主要内容,如果未能解决你的问题,请参考以下文章
Leet Code OJ 223. Rectangle Area [Difficulty: Easy]
Leet Code OJ 338. Counting Bits [Difficulty: Easy]
Leet Code OJ 20. Valid Parentheses [Difficulty: Easy]
Leet Code OJ 66. Plus One [Difficulty: Easy]