1. 程式人生 > 其它 >【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 二叉搜尋樹的最近公共祖先(Easy)(JAVA)

【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 二叉搜尋樹的最近公共祖先(Easy)(JAVA)

技術標籤:Leetcode演算法java二叉樹leetcode資料結構

【LeetCode】235. Lowest Common Ancestor of a Binary Search Tree 二叉搜尋樹的最近公共祖先(Easy)(JAVA)

題目地址: https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/

題目描述:

Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and qas the lowest node in T that has both p and qas descendants (where we allow a node to be a descendant of itself).”

Example 1:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8
Output: 6
Explanation: The LCA of nodes 2 and 8 is 6.

Example 2:

Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4
Output: 2
Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Example 3:

Input: root = [2,1], p = 2, q = 1
Output: 2

Constraints:

  • The number of nodes in the tree is in the range [2, 10^5].
  • -10^9 <= Node.val <= 10^9
  • All Node.val are unique.
  • p != q
  • p and q willexist in the BST.

題目大意

給定一個二叉搜尋樹, 找到該樹中兩個指定節點的最近公共祖先。

百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。”

解題方法

  1. 因為是二叉搜尋樹,滿足左子樹都比當前節點小,右子樹都比當前節點大
  2. 最近的祖先節點:滿足 p,q 中的較小值在左邊,較大值在右邊(都是大於等於的情況)
  3. 如果不滿足,但是當前節點比最大值還大,那肯定在左子樹
  4. 如果當前節點比最小值還小,肯定在右子樹
class Solution {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if (p.val > q.val) {
            TreeNode temp = p;
            p = q;
            q = temp;
        }
        while (root != null) {
            if (root.val >= p.val && root.val <= q.val) return root;
            if (root.val > p.val) {
                root = root.left;
            } else {
                root = root.right;
            }
        }
        return null;
    }
}

執行耗時:7 ms,擊敗了38.20% 的Java使用者
記憶體消耗:39.6 MB,擊敗了62.45% 的Java使用者

歡迎關注我的公眾號,LeetCode 每日一題更新