给定一个二叉树,判断其是否是一个有效的二叉搜索树。(写了一堆错误代码哎)
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
s = []
cur = root
temp_value = float("inf")
while cur or s:
while cur:
s.append(cur)
cur = cur.left
top = s.pop()
if top.val <= temp_value:
return False
temp_value = top.val
cur = top.right
return True
def preSearch(self, root):
print(root.val)
if root.left:
self.preSearch(root.left)
if root.right:
self.preSearch(root.right)
def midSearch(self, root):
if root.left:
self.midSearch(root.left)
print(root.val)
if root.right:
self.midSearch(root.right)
def postSearch(self, root):
if root.left:
self.postSearch(root.left)
if root.right:
self.postSearch(root.right)
print(root.val)
def non_recur_preSearch(self, root):
"""非递归前序遍历"""
s = []
cur = root
while cur or s:
while cur:
print(cur.val)
s.append(cur)
cur = cur.left
cur = s.pop()
cur = cur.right
def non_recur_midSearch(self, root):
"""非递归中序遍历"""
s = []
cur = root
while cur or s:
while cur:
s.append(cur)
cur = cur.left
cur = s.pop()
print(cur.val)
cur = cur.right
def non_recur_postSearch(self, root):
"""非递归前序遍历"""
s = []
cur = root
last = None
while cur or s:
while cur:
s.append(cur)
cur = cur.left
top = s[-1]
if not top.right or top.right == last:
s.pop()
print(top.val)
last = top
else:
cur = top.right
def non_recur_postSearch2(root):
"""
非递归形式的后序遍历方式二
然后我发现一个奇怪的现象就是你把前序反着弄就变成了后序,
我对三个树进行了一下验证,一个5个节点以及7个节点和11个节点进行了验证,都是对的,你可以试试
"""
s = []
temp = []
cur = root
while cur or s:
while cur:
print(cur.val)
temp.append(cur.val)
s.append(cur)
cur = cur.right
top = s.pop()
cur = top.left
temp.reverse()
print(temp)
def broad_search(self, root):
"""说实话层序遍历我还可以写出来,但是非递归的前中后我实在理解不了"""
q = []
if not root:
return
q.append(root)
while q:
top = q.pop(0)
print(top.val)
if top.left:
q.append(top.left)
if top.right:
q.append(top.right)
if __name__ == '__main__':
root = TreeNode(0)
# n1 = TreeNode(1)
# n2 = TreeNode(5)
# n3 = TreeNode(0)
# n4 = TreeNode(2)
# n5 = TreeNode(3)
# n6 = TreeNode(6)
#
# n1.left = n3
# n1.right = n4
#
# n2.left = n5
# n2.right = n6
#
# root.left = n1
# root.right = n2
s1 = Solution()
# s1.preSearch(root)
# s1.midSearch(root)
# s1.postSearch(root)
# print(s1.non_recur_midSearch(root))
# print(s1.non_recur_preSearch(root))
# print(s1.non_recur_postSearch(root))
# print(s1.broad_search(root))
print(s1.isValidBST(root))
# print(s1.stack)