public class GetBST {
public TreeNode root;
public GetBST(int data) {
root = new TreeNode(data);
}
public static void main(String[] args) {
/*创建根节点*/
GetBST getBST = new GetBST(3);
TreeNode x1 = new TreeNode(5);
getBST.initBst(x1);
/*创建众多子节点*/
TreeNode x2 = new TreeNode(4);
getBST.initBst(x2);
TreeNode x3 = new TreeNode(0);
getBST.initBst(x3);
TreeNode p = new TreeNode(-2);
getBST.initBst(p);
TreeNode q = new TreeNode(8);
getBST.initBst(q);
TreeNode result = lowestCommonAncestor(getBST.root, x2, q);
System.out.println(result.val);
}
/*插入搜索二叉树*/
public void initBst(TreeNode a){
TreeNode current;
current = root;
while (true) {
if (a.val >= current.val) {
if (current.right == null){
current.right = a;
return;
} else {
current = current.right;
}
} else {
if (current.left == null){
current.left = a;
return;
} else {
current = current.left;
}
}
}
}
/*搜索最小祖先*/
public static TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (p.val < root.val && q.val < root.val)
return lowestCommonAncestor(root.left, p, q);
else if (p.val > root.val && q.val > root.val)
return lowestCommonAncestor(root.right, p, q);
else
return root;
}
}
/*搜索二叉树结构*/
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
网友评论