题目

image.png

代码

  1. public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
  2. if (root == null || root.equals(p) || root.equals(q)) return root;
  3. TreeNode l = lowestCommonAncestor(root.left, p, q);
  4. TreeNode r = lowestCommonAncestor(root.right, p, q);
  5. if(l == null) return r;
  6. if(r == null) return l;
  7. return root;
  8. }