1. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q){
    2. if(root == null) return root;
    3. if(root == p || root = q) return root;
    4. //按照下面的图,认真将递归的过程在脑子中走一遍,可以帮助加深理解。
    5. TreeNode left = lowestCommonAncestor(root.left, p, q);
    6. TreeNode right = lowestCommonAncestor(root.right, p, q);
    7. if(left != null && right != null){ // p, q 分属在左右两个子树上
    8. return root;
    9. } else if(left != null){
    10. return left;
    11. } else if(right != null){
    12. return right;
    13. }
    14. return null;
    15. }

    二叉树.PNG