剑指 Offer 68 - II. 二叉树的最近公共祖先 Author: Brandon Ng Date: May 13, 2022 17:32:09 剑指 Offer 68 - II. 二叉树的最近公共祖先 236. 二叉树的最近公共祖先 题目描述同68 - I 题目但是只是单纯的二叉树 输入输出1234567输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1输出: 3解释: 节点 5 和节点 1 的最近公共祖先是节点 3。输入: root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4输出: 5解释: 节点 5 和节点 4 的最近公共祖先是节点 5。因为根据定义最近公共祖先节点可以为节点本身。 基本思路 java实现12345678910111213141516171819/** * 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 || 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; if(right == null) return left; return root; }} Tag(s): # algorithm-Easy # algorithm-树 back · home 剑指 Offer 26. 树的子结构 剑指 Offer 68 - I. 二叉搜索树的最近公共祖先