题目要求:
分析:
递归,看作整体。
- 先判断特殊情况,即整棵树为空的情况;
- 再判断当p或q为root的情况;
- 然后将左右子树分别进行递归,看作一个整体,判断它们为null和非null的情况即可。
具体代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) {
return null;
}
if(root == p || root == q) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if(left != null && right != null) {
return root;
}
if(left == null) {
return right;
}
if(right == null) {
return left;
}
return null;
}
}