算法作業HW30:LeetCode 235. Lowest Common Ancestor of a Binary Search Tree

Description:

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

 

Note:

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 nodes2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition.


Solution:

  Analysis and Thinking:

題目要求對於給定的一個二叉搜索樹,找出給出的兩個結點的最近公共祖先,可以使用遞歸的思想實現

  Steps:

1. 如果當前兩待搜索結點都小於根結點,進行右子樹遞歸

2. 如果當前兩待搜索結點都大於根結點,進行左子樹遞歸

3. 如果兩節點大小不等(一個大於根結點,一個小於),返回根結點


Codes:

class Solution {
public:
    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;
    }
};


Results:




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章