一、题目
二、代码
/**
* 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 null;
else if(left != null && right == null) return left;
else if(left == null && right!= null) return right;
else
{
return root;
}
}
}