题意以及限制条件
- 题目:
- 限制条件:
想到的所有可能解法
-
Ways_1——递归
- 时间复杂度——O(n);空间复杂度——O(n)。
对应的代码
- Ways_1
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);
return left == null ? right : right == null ? left : root;
}
}