• 边工作边刷题:70天一遍leetcode: day 85-1


    Inorder Successor in BST
    要点:这题要注意的是如果不是BST,没法从树结构上从root向那边找p,只能遍历。而根据BST,可以只走正确方向

    • 如果不检查right子树,可以从root到下,但invariant是root!=null。而检查右子树,invariant可以是root!=p

    错误点:

    • 不是找到某个>p.val,而是要找到最接近的p.val:所以loop终止条件是直到p==root or root is None,过程中只要>p.val就记录successor:这个过程的前提是p.right is None
    • 别忘了loop

    https://repl.it/CfBm/1

    # Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
    
    # Note: If the given node has no in-order successor in the tree, return null.
    
    # Hide Company Tags Pocket Gems Microsoft Facebook
    # Hide Tags Tree
    # Hide Similar Problems (M) Binary Tree Inorder Traversal (M) Binary Search Tree Iterator
    
    # 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 inorderSuccessor(self, root, p):
            """
            :type root: TreeNode
            :type p: TreeNode
            :rtype: TreeNode
            """
            if p.right:
                p = p.right
                while p.left:
                    p=p.left
                return p
            else:
                succ = None
                while root!=p:
                    if p.val<root.val:
                        succ = root
                        root = root.left
                    else:
                        root = root.right
                return succ
    
  • 相关阅读:
    字符串基本操作
    条件、循环、函数定义 练习
    turtle库基础练习
    Python基础练习
    AutoLayout 教程
    Mac上最佳的SVN管理工具:Cornerstone
    图片上传 关于压缩的问题
    关于单元测试的问题
    获取ios设备的当前IP地址
    关于项目使用ARC的管理方式
  • 原文地址:https://www.cnblogs.com/absolute/p/5815765.html
Copyright © 2020-2023  润新知