Medium草稿★★★★★O(h) 時間 · O(1) 空間
TreeBSTDFSRecursion
Patterns🌳 樹形 DFS
尚未複習過

解法已隱藏 — 先讀題目敘述、自己想想看,再點上方按鈕揭曉。

235Lowest Common Ancestor of a Binary Search TreeTreesMediumTrees

給定一棵二元搜尋樹 (BST) 和兩個節點 p、q,找到它們的最低共同祖先 (LCA)。LCA 定義為同時是 p 和 q 祖先的最深節點。

Example:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 Output: 6

Intuition

TIP

利用 BST 性質:若 p 和 q 分別在當前節點的兩側,當前節點就是 LCA。

Approaches

1. Recursive — O(h) / O(h)
  • Idea: 根據 BST 性質遞迴搜尋
  • Time: O(h),h 為樹高
  • Space: O(h),遞迴堆疊
class Solution {
    fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
        if (root == null || p == null || q == null) return null
        if (p.`val` < root.`val` && q.`val` < root.`val`) {
            return lowestCommonAncestor(root.left, p, q)
        }
        if (p.`val` > root.`val` && q.`val` > root.`val`) {
            return lowestCommonAncestor(root.right, p, q)
        }
        return root
    }
}
⭐ 2. Iterative — O(h) / O(1)
  • Idea: 同樣利用 BST 性質,但用迴圈代替遞迴,節省堆疊空間
  • Time: O(h)
  • Space: O(1)
class Solution {
    fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
        var current = root
        while (current != null) {
            if (p!!.`val` < current.`val` && q!!.`val` < current.`val`) {
                current = current.left
            } else if (p.`val` > current.`val` && q!!.`val` > current.`val`) {
                current = current.right
            } else {
                return current
            }
        }
        return null
    }
}

🔑 Takeaways