
解题思路:找祖先从底向上递归后序遍历查找,遇到p,q或者空节点就直接返回对应值,当某个节点的左子树、右子树都返回了值,那么就说明该节点就是最近祖先节点,然后把该节点的值继续往上传,直到根节点返回结果。
/*** 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 == p || root==q || root==null) 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 && right!= null) return right;if(left!=null && right==null) return left;else return root;}
}