zoukankan      html  css  js  c++  java
  • 235. Lowest Common Ancestor of a Binary Search Tree

    https://leetcode.com/problems/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.

    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.

    Hint:

    There are four relationships of subnodes p, q and root node root. 

    1) Two subnodes are on the left subtree. (see node 1, 4)

    2) Two subnodes are on the right subtree. (see node 7, 9)

    3) One subnode is on the left subtree while another is on the right subtree. (see node 1, 7)

    4) The value of one subnode is euqal to the value of root node.  (see node 2, 4)

    Under scenario 1 and 2, the current node the most recent ancestor, while under scenario  2 and 4, recursion on the left or right tree is needed to find the LCA.

    Time/Space complexity: O(h) where h is the height of the tree. 

    Sol:

    Iteration.

    # Definition for a binary tree node.
    class TreeNode(object):
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    class Solution(object):
        def lowestCommonAncestor(self, root, p, q):
            """
            :type root: TreeNode
            :type p: TreeNode
            :type q: TreeNode
            :rtype: TreeNode
            """
            while root:
                if min(q.val, p.val) > root.val:
                    root = root.right
                elif max(q.val, p.val) < root.val:
                    root = root.left
                else:
                    return root
            return None

    Note:

    1 If both values of sub nodes are greater than the value of the root, the new root is the right child of the root. 

    If both values of sub nodes are smaller than the value of the root, the new root is the left child of the root. 

    2 Can not write "return" in front of root = root.right/left. This is a iterate process, do not return anything until the process is finished. 

    Sol 2:

    Recursion

    # Definition for a binary tree node.
    class TreeNode(object):
        def __init__(self, x):
            self.val = x
            self.left = None
            self.right = None
    
    class Solution(object):
        def lowestCommonAncestor(self, root, p, q):
            """
            :type root: TreeNode
            :type p: TreeNode
            :type q: TreeNode
            :rtype: TreeNode
            """
            while root:
                if min(q.val, p.val) > root.val:
                    return self.lowestCommonAncestor(root.right, p, q)
                elif max(q.val, p.val) < root.val:
                    return self.lowestCommonAncestor(root.left, p, q)
                else:
                    return root
            return None

    Note:

    1 Write "return" before calling the function. This is a recursive process, so following process replies on previous values. Do return values in each recursion.   

  • 相关阅读:
    Git Bash 常用指令
    C/C++连接MySQL数据库执行查询
    question from asktom
    ORACLE AWR报告
    查看oracle表索引
    ORACLE数据库关闭与启动
    SYS vs SYSTEM and SYSDBA vs SYSOPER
    【面试】二叉树遍历的非递归实现
    快速排序的非递归实现
    MySQL数据库基础
  • 原文地址:https://www.cnblogs.com/prmlab/p/6951225.html
Copyright © 2011-2022 走看看