力扣 LeetCode 236. 二叉树的最近公共祖先(Day10:二叉树)
解题思路:
后序遍历
注意:
p和q其中一个就是它们的公共祖先的情况也考虑到了,假设q是公共祖先,遇到q就直接返回,相当于是下面一边为空,一边不为空的情况,返回不为空就一边即可
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
return recur(root, p, q);
}
public TreeNode recur(TreeNode root, TreeNode p, TreeNode q) {
if (root == null) return null;
if (root == p || root == q) return root;
TreeNode left = recur(root.left, p, q);
TreeNode right = recur(root.right, p, q);
if (left != null && right != null) return root;
if (left == null && right != null) return right;
if (left != null && right == null) return left;
else return null;
}
}