当前位置: 代码迷 >> 综合 >> LeetCode 235 Lowest Common Ancestor of a Binary Search Tree
  详细解决方案

LeetCode 235 Lowest Common Ancestor of a Binary Search Tree

热度:121   发布时间:2023-10-28 04:38:47.0

思路

由于是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)

  相关解决方案