/**
* 二叉树中两个节点的最低公共祖节点
*/
public class LowerAncestors {

public static Node lowerAncestors(Node head, Node o1, Node o2) {
return process(head, o1, o2).result;
}

private static ResultInfo process(Node node, Node o1, Node o2) {
if (node == null) {
return new ResultInfo(null, false, false);
}
ResultInfo leftInfo = process(node.left, o1, o2);
ResultInfo rightInfo = process(node.right, o1, o2);

boolean findO1 = node == o1 || leftInfo.findO1 || rightInfo.findO1;
boolean findO2 = node == o2 || leftInfo.findO2 || rightInfo.findO2;
Node result = leftInfo.result != null ? leftInfo.result : rightInfo.result != null ? rightInfo.result : null;
result = result == null && findO1 && findO2 ? node : result;
return new ResultInfo(result, findO1, findO2);
}

public static class ResultInfo {

public Node result;

public boolean findO1;

public boolean findO2;

public ResultInfo(Node node, boolean b1, boolean b2) {
result = node;
findO1 = b1;
findO2 = b2;
}

}

public static class Node {

public int value;

public Node left;

public Node right;

public Node(int data) {
this.value = data;
}

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */