题目链接:https://leetcode.cn/problems/lowest-common-ancestor-of-a-binary-tree/
方法一 递归-后序遍历
1 方法思想
2 代码实现
/**
* 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.val == p.val || root.val == q.val) {
return root;
}
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left == null && right == null) {
return null;
} else if (left == null && right != null) {
return right;
} else if (left != null && right == null) {
return left;
} else {
return root;
}
}
}
3 复杂度分析
时间复杂度:
空间复杂度: