public class Main {
private static TreeNode<Integer> ans;
private static boolean dfs(TreeNode<Integer> root, TreeNode<Integer> p, TreeNode<Integer> q) {
if (root == null) {
return false;
}
boolean lson = dfs(root.left, p, q);
boolean rson = dfs(root.right, p, q);
if ((lson && rson) || ((root.val.equals(p.val) || root.val.equals(q.val)) && (lson || rson))) {
ans = root;
}
return lson || rson || (root.val.equals(p.val) || root.val.equals(q.val));
}
public static TreeNode<Integer> lowestCommonAncestor(TreeNode<Integer> root, TreeNode<Integer> p, TreeNode<Integer> q) {
dfs(root, p, q);
return ans;
}
public static void main(String[] args) {
TreeNode<Integer> root = new TreeNode<Integer>(2);
root.left = new TreeNode<>(1);
root.right = new TreeNode<>(3);
System.out.println(lowestCommonAncestor(root, root.left, root.right).val);
}
}
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交