• LeetCode#235 Lowest Common Ancestor of a Binary Search Tree


    Problem Definition:

      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).”

    思路:由根节点开始:

      1) 如果根节点的值等于其中一个节点,则根节点就是要找的最低公共祖先,返回它;

      2) 排序,确保p<=q;

      3) 如果根节点值大于p而小于q,则p和q分别在根节点的左右子树,根节点就是要找的最低公共祖先,返回它;

      4) 如果根节点值大于较大的q,则p和q都在根节点的左子树,令根节点左子节点为新的根节点;如果根节点值小于较小的p,则p和q都在根节点的右子树

        另根节点右子节点为新的根节点;

      5)递归地进行1)-->4).

    代码:

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        # @param {TreeNode} root
        # @param {TreeNode} p
        # @param {TreeNode} q
        # @return {TreeNode}
        def lowestCommonAncestor(self, root, p, q):
            if (root.val==p.val) or (root.val==q.val):
                return root
            if p.val>q.val:
                p,q=q,p
            if p.val<root.val and root.val<q.val:
                return root
            if root.val>q.val:
                root=root.left
            if root.val<p.val:
                root=root.right
            if root!=None:
                return self.lowestCommonAncestor(root, p, q)
            
                

      

  • 相关阅读:
    学生党可以申请的免费学习资源
    ms16-032漏洞复现过程
    宽字节注入浅浅谈!
    access数据库之cookie注入
    web渗透学习方向
    最简单的注入
    snapde的批量数据运算公式
    snapde的批量文件数据过滤保存功能
    五、Snapman多人协作电子表格之——Python脚本
    超大文本文件浏览器Snaptext,支持不限制大小的文本文件浏览
  • 原文地址:https://www.cnblogs.com/acetseng/p/4648741.html
Copyright © 2020-2023  润新知