对二叉查找树找到两个节点的最小公共祖先:可以根据二叉查找树的性质:左子树的节点值比根节点的值小,右子树的节点值比根节点值大
public class BinarySearchTree<T extends Comparable> { BinaryTreeNode<T> root; public BinarySearchTree(BinaryTreeNode<T> root) { this.root = root; } public BinaryTreeNode<T> getRoot() { return root; } /* * 两个不同节点的最小祖先 思路: left比root节点大, 遍历root的右子树,max比root节点小,遍历root左子树 * 不满足以上情况表示找到他们的祖先,并返回 */ public T getLowestCommonAncestor(T n1, T n2) { //分别以递归和非递归实现 //return findNodeWithNoCursion(root, n1, n2); return findNodeWithCursion(root, n1, n2); } private T findNodeWithCursion(BinaryTreeNode<T> node, T n1, T n2) { if (node == null) { return null; } if (n1.compareTo(node.data) < 0 && n2.compareTo(node.data) < 0) { return findNodeWithCursion(node.left, n1, n2); } if (n1.compareTo(node.data) > 0 && n2.compareTo(node.data) > 0) { return findNodeWithCursion(node.right, n1, n2); } return node.data; } private T findNodeWithNoCursion(BinaryTreeNode<T> node, T n1, T n2) { //若n1 > n2, 调换位置 if (n1.compareTo(n2) > 0) { T tmp = n1; n1 = n2; n2 = tmp; } while (true) { if (n1.compareTo(node.data) > 0) { node = node.right; } else if (n2.compareTo(node.data) < 0) { node = node.left; } else { return node.data; } } }
public static void main(String[] args) { BinaryTreeNode<Integer> root = new BinaryTreeNode<Integer>(5); root.left = new BinaryTreeNode<Integer>(2); root.right = new BinaryTreeNode<Integer>(6); root.left.left = new BinaryTreeNode<Integer>(1); root.left.right = new BinaryTreeNode<Integer>(4); root.left.right.left = new BinaryTreeNode<Integer>(3); BinarySearchTree<Integer> tree = new BinarySearchTree<Integer>(root); System.out.println(tree.getLowestCommonAncestor(1, 6)); //5 }
}
以下是二叉树节点的类的定义
public class BinaryTreeNode<T extends Comparable> { public T data; public BinaryTreeNode<T> left; public BinaryTreeNode<T> right; public BinaryTreeNode() { } public BinaryTreeNode(T data) { this.data = data; } public BinaryTreeNode(T data, BinaryTreeNode<T> right, BinaryTreeNode<T> left) { this.data = data; this.left = left; this.right = right; } public T getData() { return data; } public void setData(T data) { this.data = data; } public BinaryTreeNode<T> getLeft() { return left; } public void setLeft(BinaryTreeNode<T> left) { this.left = left; } public BinaryTreeNode<T> getRight() { return right; } public void setRight(BinaryTreeNode<T> right) { this.right = right; }
时间: 2025-01-12 23:06:26