1. 程式人生 > >[Lintcode]95. Validate Binary Search Tree/[Leetcode]98. Validate Binary Search Tree

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

date rmi 沒有 append etc return must follow ram

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