leetcode-lowest-common-ancestor-bst

题目大意

  https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

  给你一棵二叉查找树,和树上的两个节点,求这两个节点的最近邻祖先。

题目分析

  递归,要充分利用二叉查找树的性质。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* 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) {
if(root == null || p == null || q == null) {
return null;
}
if(root.val == p.val || root.val == q.val) {
return root;
}
if((root.val < p.val && root.val > q.val) || (root.val < q.val && root.val > p.val)) {
return root;
}
if(root.val < p.val && root.val < q.val) {
return lowestCommonAncestor(root.right, p, q);
}
return lowestCommonAncestor(root.left, p, q);
}
}