题目描述:
10 8 6 0 0 9 0 0 20 15 0 0 0
6 15
给定一棵树,同时给出树中的两个结点,求它们的最低公共祖先。
6 15
存在, 10
基本思想为:从树根开始
1、该节点的值为t,如果t大于t1和t2,说明t1和t2都位于t的左侧,所以它们的共同祖先必定在t的左子树中,从t.left开始搜索;
2、如果t小于t1和t2,说明t1和t2都位于t的右侧,那么从t.right开始搜索;
3、如果t1<t< t2,说明t1和t2位于t的两侧,那么该节点t为公共祖先。
如果t1是t2的祖先,那么应该返回t1的父节点;同理,如果t2是t1的祖先,应该返回t2的父节点。
/**
* 二叉树中任意两个节点的最近公共祖先
*
* 如果二叉树为二叉查找树
*
*/
public static boolean LowestCommonAncestor(BinaryTreeNode root, int a, int b) {
BinaryTreeNode parent = null;
BinaryTreeNode curRoot = root;
// a, b 有序
if(a > b) {
int tmp = a;
a = b;
b = tmp;
}
while(curRoot != null) {
// 如果当前结点大于a,b , 则在左子树
if(curRoot.elem > b) {
parent = root;
curRoot = curRoot.left;
// 如果当前结点小于a,b , 则在右子树
} else if(curRoot.elem < a) {
parent = root;
curRoot = curRoot.right;
// 如果当前结点等于a,b , 则在返回当前结点的父节点
} else if(curRoot.elem == a || curRoot.elem == b) {
result = parent.elem;
return true;
// 如果当前结点正好介于a, b 之间
} else {
result = curRoot.elem;
return true;
}
}
return false;
}