码迷,mamicode.com
首页 > 其他好文 > 详细

[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

时间:2019-02-14 22:12:44      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:eve   pre   des   contain   ret   pen   lse   难度   http   

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

标签:eve   pre   des   contain   ret   pen   lse   难度   http   

原文地址:https://www.cnblogs.com/siriusli/p/10380853.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!