我的LeetCode代码仓:https://github.com/617076674/LeetCode
原题链接:https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/description/
题目描述:
知识点:二叉树、递归
思路:递归寻找二叉树的最近公共祖先
如果root为null或者p、q中有一个就是root,直接返回root即可。
在左子树中寻找p、q的最近公共祖先,记录所得结果为left。
在右子树中寻找p、q的最近公共祖先,记录所得结果为right。
如果left为null,直接返回right即可。
如果right为null,直接返回left即可。
如果left和right均不为null,我们应该直接返回root。
时间复杂度是O(n),其中n为二叉树中的节点数。空间复杂度是O(h),其中h为二叉树的高度。
JAVA代码:
public 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(null == left){
return right;
}
if(null == right){
return left;
}
return root;
}
}
LeetCode解题报告: