Advertisement
jinhuang1102

98. Validate Binary Search Tree

Nov 13th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.69 KB | None | 0 0
  1. #98. Validate Binary Search Tree
  2. #   这道题目前我掌握了两种办法。
  3. #   方法一是利用BST的性质,BST 的 inorder traversal 是一个 sorted array。
  4. #   所以,利用 inorder traversal 产生 sorted array, 然后验证array是否是sorted
  5.  
  6. class Solution:
  7.     def inorder(self, root, res):
  8.         if not root:
  9.             return
  10.  
  11.         self.inorder(root.left, res)
  12.         res.append(root.val)
  13.         self.inorder(root.right, res)
  14.  
  15.         return
  16.  
  17.     def isValidBST(self, root):
  18.         """
  19.        :type root: TreeNode
  20.        :rtype: bool
  21.        """
  22.         if not root:
  23.             return True
  24.  
  25.         res = []
  26.         self.inorder(root, res)
  27.  
  28.         for i in range(0, len(res)):
  29.             if i > 0 and res[i] <= res[i - 1]:
  30.                 return False
  31.  
  32.         return True
  33.  
  34. #   方法二没有用到 inorder traverseal, 是用 DFS 来实现,
  35. #   根据此题给出的BST性质所知:
  36. #       left < root < right
  37. #   就是利用其本身性质来做,初始化时带入系统最大值和最小值,在递归过程中换成它们自己的节点值
  38.  
  39. import sys
  40. class Solution2:
  41.     def BFS(self, root, minValue, maxValue):
  42.         if not root:
  43.             return True
  44.  
  45.         if root.val <= minValue or root.val >= maxValue:
  46.             return False
  47.  
  48.         left = self.BFS(root.left, minValue, root.val)
  49.         right = self.BFS(root.right, root.val, maxValue)
  50.  
  51.         return left and right
  52.  
  53.     def isValidBST(self, root):
  54.         """
  55.        :type root: TreeNode
  56.        :rtype: bool
  57.        """
  58.         if not root:
  59.             return True
  60.         res = self.BFS(root, -sys.maxsize, sys.maxsize)
  61.         return res
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement