这道题判断一个二叉树是不是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
本文介绍了一种通过中序遍历检查二叉树是否为二叉搜索树(BST)的方法。采用递归方式实现中序遍历,并将节点值存入数组中,最后检查数组元素是否依次递增。
224

被折叠的 条评论
为什么被折叠?



