思路
由于是BST,思路相比与236题有所简化。
只需要判断2个目标是否都在同一分支即可。
递归实现
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {
// recursivelypublic TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(p.val > root.val && q.val > root.val)return lowestCommonAncestor(root.right, p, q);if(p.val < root.val && q.val < root.val)return lowestCommonAncestor(root.left, p, q);return root;}
}
时间复杂度O(n)
空间复杂度O(n)
迭代实现
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
class Solution {
// iterativelypublic TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
while(root != null) {
if(p.val > root.val && q.val > root.val)root = root.right;else if(p.val < root.val && q.val < root.val)root = root.left;elsereturn root;}return null;}
}
时间复杂度O(n)
空间复杂度O(1)