Question
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
Example 1:
Example 2:
Solution
Naive
- # Definition for a binary tree node.
- class TreeNode:
- def __init__(self, x):
- self.val = x
- self.left = None
- self.right = None
- class Solution:
- def isValidBST(self, root):
- if not root:
- return True
- inf = float('inf')
- queue = [(root, inf, -inf)]
- while queue:
- n, max_v, min_v = queue.pop(0)
- print("N={}; max={}; min={}".format(n.val, max_v, min_v))
- if n.val >= max_v or n.val <= min_v:
- return False
- if n.left:
- if n.left.val >= n.val:
- return False
- queue.append((n.left, min(max_v, n.val), min_v))
- if n.right:
- if n.right.val <= n.val:
- return False
- queue.append((n.right, max_v, max(min_v, n.val)))
- return True
- def build_t(elements):
- datas = []
- datas.extend(elements)
- root = TreeNode(datas.pop(0))
- queue = [root]
- while queue and datas:
- n = queue.pop(0)
- v1 = datas.pop(0)
- v2 = datas.pop(0)
- if v1 is not None:
- n.left = TreeNode(v1)
- queue.append(n.left)
- if v2 is not None:
- n.right = TreeNode(v2)
- queue.append(n.right)
- return root
- if __name__ == '__main__':
- s = Solution()
- for datas, ans in [
- ([2, 1, 3], True),
- ([5, 1, 4, None, None, 3, 6], False),
- ([10, 5, 15, None, None, 6, 20], False),
- ([10, 5, 15, None, None, 14, 20], True),
- ([3, 1, 5, 0, 2, 4, 6, None, None, None, 3], False)
- ]:
- root = build_t(datas)
- rel = s.isValidBST(root)
- print("{}: {}".format(datas, rel))
- assert ans == rel
Golden (link)
- class Solution:
- def isValidBST(self, root):
- """
- :type root: TreeNode
- :rtype: bool
- """
- def helper(node, lower = float('-inf'), upper = float('inf')):
- if not node:
- return True
- val = node.val
- if val <= lower or val >= upper:
- return False
- if not helper(node.right, val, upper):
- return False
- if not helper(node.left, lower, val):
- return False
- return True
- return helper(root)
Supplement
* 【LeetCode】98. Validate Binary Search Tree 解题报告(Python & C++ & Java)
* Youtube - LeetCode 98. Validate Binary Search Tree...rithm Explained) by Nick White
沒有留言:
張貼留言