1.题目
给定二叉树,计算出两个给定的结点的公共结点。
2.解法–递归
从根节点开始,递归遍历左右子树,查看是否从该节点能遍历到这两个给定的结点中的至少一个,返回能遍历到的指定节点,如果都能遍历到,返回的是最低父节点。当然能否遍历到是依靠下层遍历的结果的。具体看代码:
public static Tree beginFind(Tree node, Tree oneNode, Tree anotherNode) {
if (node == null) {
return null;
}
// 当前节点正好是关心的两个节点中的一个,返回当前节点,表示找到了一个节点
if (node == oneNode || node == anotherNode) {
return node;
}
// 看当前节点的左子树是否包含两个指定节点
Tree leftNode &