LC.P235[二叉搜索树的最近公共祖先]

方法一:DFS

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 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) {
int x = root.val;
if (p.val < x && q.val < x) return lowestCommonAncestor(root.left, p, q);
if (p.val > x && q.val > x) return lowestCommonAncestor(root.right, p, q);
return root;
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$