236. Lowest Common Ancestor of a Binary Tree
分情况讨论,第一句是对于空节点的条件(递归出口条件)。后面是中间节点的情况,root的左边和右边接住返回值之后,判断是否为空,若两边都不为空,那么返回root。如果任意一边有值,就返回有值的一边。
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q) return root;
root.left = lowestCommonAncestor(root.left, p, q);
root.right = lowestCommonAncestor(root.right, p, q);
if (root.left != null && root.right != null) {
return root;
}
return (root.left == null) ? root.right : root.left;
}