美文网首页
Is Binary Search Tree Or Not

Is Binary Search Tree Or Not

作者: GakkiLove | 来源:发表于2018-05-15 20:24 被阅读0次

    Determine if a given binary tree is binary search tree.

    Assumptions

    There should no be duplicate keys in binary search tree.
    You can assume the keys stored in the binary search tree can not be Integer.MIN_VALUE or Integer.MAX_VALUE.

    Corner Cases

    What if the binary tree is null? Return true in this case.

    class Solution(object):
      def isBST(self, root):
        if not root:
          return True
        return self.helper(root,float('-inf'),float('inf'))
      
      def helper(self,root,min,max):
        if not root:
          return True
        if root.val >= max or root.val <= min:
          return False
        return self.helper(root.left,min,root.val) and self.helper(root.right,root.val,max)
    

    相关文章

      网友评论

          本文标题:Is Binary Search Tree Or Not

          本文链接:https://www.haomeiwen.com/subject/prwydftx.html