[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree
Posted siriusli
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree相关的知识,希望对你有一定的参考价值。
95. Validate Binary Search Tree/98. Validate Binary Search Tree
- 本题难度: Easy
- Topic: Binary Tree
Description
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node‘s key.
The right subtree of a node contains only nodes with keys greater than the node‘s key.
Both the left and right subtrees must also be binary search trees.
A single node tree is a BST
Example
An example:
2
/
1 4
/
3 5
The above binary tree is serialized as {2,1,4,#,#,3,5} (in level order).
我的代码
# 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: ‘TreeNode‘) -> ‘bool‘:
def inorder(self,root,res = []):
if root is None:
return res
if root.left is not None:
res = self.inorder(root.left,res)
res.append(root.val)
if root.right is not None:
res = self.inorder(root.right,res)
return res
def isValidBST(self, root):
# write your code here
if root is None:
return True
res = self.inorder(root,[])
print(res)
sortres = sorted(res)
print(res)
return sortres == res and (len(res) == len(set(res)))
别人的代码
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
"""
@param root: The root of binary tree.
@return: True if the binary tree is BST, or false
"""
def isValidBST(self, root, left = float(‘-inf‘), right = float(‘inf‘)):
if not root:
return True
if root.val<left or root.val>right:
return False
return self.isValidBST(root.left,left,min(right,root.val)) and self.isValidBST(root.left,max(left,root.val),right)
思路
我的思路是,中序遍历为有序且没有重复数字。
其实可以直接用比左子树大,比右子树小来判断
以上是关于[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree的主要内容,如果未能解决你的问题,请参考以下文章
CCI4.5/LintCode Validate Binary Search Tree