题目描述

题解
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val
* TreeNode left
* TreeNode right
* TreeNode(int x) { val = x
* }
*/
// 本题和【剑指offer】68.2 二叉树的最近公共祖先 一模一样
// 看到https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/solution/236-er-cha-shu-de-zui-jin-gong-gong-zu-xian-hou-xu/
// 图文并茂写得很好,不理解可以看看。
//
// 执行用时:7 ms, 在所有 Java 提交中击败了99.93%的用户
// 内存消耗:40.6 MB, 在所有 Java 提交中击败了55.10%的用户
class Solution {
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)
return right
else if (right == null)
return left
return root
}
}