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;
}
}