题目
递归思想
递归找p和q结点,root.left去找当前根节点的左子树,root.right去找当前根节点的右子树。分为四种情况
- left和right均为null 说明当前根节点下没有p和q 返回null
- left为null 说明p和q均不在left的子树中 返回right
- right为null 说明p和q均不在right的子树中 返回left
- left和right都不为null 说明p和q在当前root的异侧 返回当前root
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || 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 null;
if (left == null) return right;
if (right == null) return left;
return root;//左右均不为空
}