[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)))
            
        

别人的代码

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

思路
我的思路是,中序遍历为有序且没有重复数字。
其实可以直接用比左子树大,比右子树小来判断

posted @ 2019-02-14 21:31  siriusli  阅读(103)  评论(0编辑  收藏  举报