这道题判断一个二叉树是不是BST。用中序遍历成为一个数组,看是不是每个值都比后面小就好了。代码如下:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
a = []
def search(root):
if root == None:
return True
if root.left != None:
search(root.left)
a.append(root.val)
if root.right != None:
search(root.right)
search(root)
print a
if len(a) == 1:
return True
for i in range(len(a) -1):
if a[i] >= a[i + 1]:
return False
else:
return True