题目: 给定一棵二叉树的头结点head,和另外两个节点a和b。返回a和b的最低公共祖先
题解:
public class Code8_LowestAncestor {
public static class Node {
int value;
Node left;
Node right;
public Node(int v) {
value = v;
}
}
public static class Info {
boolean findA;//是否发现了a节点
boolean findB;//是否发现了b节点
Node ans;//搜集答案
public Info(boolean findA, boolean findB, Node ans) {
this.findA = findA;
this.findB = findB;
this.ans = ans;
}
}
public static Node solve(Node head, Node a, Node b) {
return process(head, a, b).ans;
}
public static Info process(Node x, Node a, Node b) {
if (x == null)
return new Info(false, false, null);
Info leftInfo = process(x.left, a, b);
Info rightInfo = process(x.right, a, b);
boolean findA = (x == a) || leftInfo.findA || rightInfo.findA;
boolean findB = (x == b) || leftInfo.findB || rightInfo.findB;
Node ans = null;
if (leftInfo.ans != null) {
ans = leftInfo.ans;
} else if (rightInfo.ans != null) {
ans = rightInfo.ans;
} else {
if (findA && findB) {
ans = x;
}
}
return new Info(findA, findB, ans);
}
}