LeetCode(236):二叉树的最近公共祖先
题目

题解
目前为了训练递归思想,树的题解都使用递归实现。
/**
此题目前是我遇到到,最考验递归思想掌握程度的题目。
条件结束语句的判断。如何分解为子问题,都是非常值得思考的。
*/
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){
return right;
}
if(right == null){
return left;
}
return root;
}
}
本文详细解析了LeetCode上编号为236的题目:二叉树的最近公共祖先。通过递归的方式实现了对该问题的有效解决,并强调了递归思想在问题分解和条件判断中的关键作用。
788

被折叠的 条评论
为什么被折叠?



