Skip to content

Commit 9fbd628

Browse files
author
programmerhjh
committed
日常水题(腾讯秋招50道)
1 parent ea4f67a commit 9fbd628

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/entity/TreeNode.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
package entity;
2+
3+
public class TreeNode {
4+
public int val;
5+
public TreeNode left;
6+
public TreeNode right;
7+
TreeNode(int x) { val = x; }
8+
}
9+
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package myleetcode;
2+
3+
import entity.TreeNode;
4+
5+
/**
6+
* 二叉搜索树的最近公共祖先
7+
* @author acer
8+
*
9+
*/
10+
public class LowestCommonAncestorOfABinarySearchTree {
11+
12+
TreeNode res = null;
13+
14+
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
15+
lca(root, p, q);
16+
return res;
17+
}
18+
19+
public void lca(TreeNode root, TreeNode p, TreeNode q) {
20+
if ((root.val - p.val) * (root.val - q.val) <= 0) {
21+
res = root;
22+
} else if (root.val < p.val && root.val < q.val) {
23+
lca(root.right, p, q);
24+
} else {
25+
lca(root.left, p, q);
26+
}
27+
}
28+
}

0 commit comments

Comments
 (0)