1. 程式人生 > >【Leetcode】235. Lowest Common Ancestor of a Binary Search Tree

【Leetcode】235. Lowest Common Ancestor of a Binary Search Tree

tween target amp des esc blog cor 循環 ive

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 v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself

).”

        _______6______
       /                  ___2__          ___8__
   /      \        /         0      _4       7       9
         /           3   5

For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.

Tips:找到一棵二叉查找樹中兩個結點的最低公共祖先。

解決方案:二叉查找樹是一個已經排好序的二叉樹,所有左子樹結點都小於父結點,所有右子樹結點都大於父節點,所以,只需要比較當前結點與p、q結點val的大小進行比較。若p、q的值都小於當前節點,那麽最低公共祖先一定在當前節點的左子樹上,相反則在右子樹上。

方案一:使用循環:

 public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
            while (true) {
                if (root.val > p.val && root.val > q.val)
                    root 
= root.left; else if (root.val < p.val && root.val < q.val) root = root.right; else return root; } }

方案二: 使用遞歸:

public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        TreeNode ans = root;
        if (root.val > p.val && root.val > q.val) {
            ans = lowestCommonAncestor(root.left, p, q);
        } else if (root.val < p.val && root.val < q.val) {
            ans = lowestCommonAncestor(root.right, p, q);
        } else {
            ans = root;
        }
        return ans;
    }

【Leetcode】235. Lowest Common Ancestor of a Binary Search Tree