1.二叉搜索树
public static TreeNode getLastCommonNode(TreeNode pRoot, TreeNode pLeft, TreeNode pRight){
TreeNode treeNode = null;
if(pRoot == null || pLeft.val > pRight.val){
return null;
}
if(pRoot.val >= pRight.val){
treeNode = getLastCommonNode(pRoot.left, pLeft, pRight);
}
if(pRoot.val <= pLeft.val){
treeNode = getLastCommonNode(pRoot.right, pLeft, pRight);
}
if(pRoot.val >= pLeft.val && pRoot.val <= pRight.val){
return pRoot;
}
return treeNode;
}
2.普通二叉树
public class T68 {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(2);
TreeNode t3 = new TreeNode(3);
TreeNode t6 = new TreeNode(6);
TreeNode t4 = new TreeNode(4);
TreeNode t5 = new TreeNode(5);
t1.left = t2;
t1.right = t3;
t2.left = t4;
t2.right=t5;
t3.left = t6;
System.out.println(getLastCommonNode(t1, t4, t6).val);
}
public static TreeNode getLastCommonNode(TreeNode pRoot,TreeNode pLeft,TreeNode pRight){
if(pRoot==null||pRoot==pLeft||pRoot==pRight){
return pRoot;
}
TreeNode left=getLastCommonNode(pRoot.left,pLeft,pRight);
TreeNode right=getLastCommonNode(pRoot.right,pLeft,pRight);
if(left==null){
return right;
}
if(right==null){
return left;
}
return pRoot;
}
}