节点类
@Data
public class Node {
private int value;
private Node left;
private Node right;
public Node() {
}
public Node(Node left, Node right, int value) {
this.left = left;
this.right = right;
this.value = value;
}
public Node(int value){
this.value=value;
}
}
二叉搜索树实现
public class BinarySortTree {
private Node root = null;
//构造二叉搜索树
public void insertBST(int key) {
Node p = root;
Node prev = null; //查找节点的前一个节点
while (p != null) {
prev = p;
if (key < p.getValue())
p = p.getLeft();
else if (key > p.getValue())
p = p.getRight();
else
return;
}
if (root == null)
root = new Node(key);
else if (key < prev.getValue())
prev.setLeft(new Node(key));
else prev.setRight(new Node(key));
}
/**
* 中序遍历
*/
public void nrInOrderTraverse() {
Stack<Node> stack = new Stack<Node>();
Node node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.getLeft();
}
node = stack.pop();
System.out.println(node.getValue());
node = node.getRight();
}
}
//找最近公共节点
public Node lowestCommonAncestor(Node root, Node p, Node q) {
while (root != null && root.getValue() != -1) {
if (root.getValue() > p.getValue() && root.getValue() > q.getValue()) {
//都比根节点值小,去根节点的左子树继续找
root = root.getLeft();
} else if (root.getValue() < p.getValue() && root.getValue() < q.getValue()) {
//都比根节点值大,去根节点的右子树继续找
root = root.getRight();
} else {
//根节点的值大于p而小于q,说明此时的根节点即为最近公共祖先。
return root;
}
}
return null;
}
public static void main(String[] args) {
BinarySortTree bst = new BinarySortTree();
int[] num = {45, 12, 37, + 24, 3, 53, 100, 61, 55, 90, 78};
Scanner scan = new Scanner(System.in);
for (int i = 0; i < num.length; i++) {
bst.insertBST(num[i]);
}
Node node1 = new Node(null, null, 3);
Node node2 = new Node(null, null, 37);
bst.nrInOrderTraverse();
System.out.println("------------");
Node node = bst.lowestCommonAncestor(bst.root, node1, node2);
System.out.println("最近公共节点为:" + node.getValue());
}
}