Problem :

https://www.hackerrank.com/challenges/is-binary-search-tree/problem


My Solution :

#!/usr/bin/env python3

""" Node is defined as
class node:
  def __init__(self, data):
      self.data = data
      self.left = None
      self.right = None
"""

def check_binary_search_tree_(root, m=-1, M=10001):
    if root == None:
        return True
    if root.left:
        if not (m < root.left.data < root.data):
            return False
    if root.right:
        if not (root.data < root.right.data < M):
            return False
    return check_binary_search_tree_(root.left, m, root.data) and \
           check_binary_search_tree_(root.right, root.data, M)


My Solution2 :

중위 순회를 이용한 방법

#!/usr/bin/env python3

""" Node is defined as
class node:
  def __init__(self, data):
      self.data = data
      self.left = None
      self.right = None
"""

last = -1

def check_binary_search_tree_(root):
    global last
    if not root:
        return True
    if not check_binary_search_tree_(root.left):
        return False
    if last >= root.data:
        return False
    last = root.data
    if not check_binary_search_tree_(root.right):
        return False
    return True