zoukankan      html  css  js  c++  java
  • 边工作边刷题: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
    
  • 相关阅读:
    linux笔记
    初探hook的键盘获取
    python pyHook安装
    转: ZigBee/Z-Stack CC2530实现低功耗运行的配置简介
    三种zigbee网络架构详解
    adc verilog spi 时序
    dac verilog ad5601
    verilog 三段式状态机的技巧
    fpga 状态机 检测1011序列
    lattice diamond fpga 状态机的理解
  • 原文地址:https://www.cnblogs.com/absolute/p/5815765.html
Copyright © 2011-2022 走看看