Example 1:
2
/ \
1 3
Input: [2,1,3]
Output: true
Example 2:
- 5
/ \
1 4
– / \
*3 6
Input: [5,1,4,null,null,3,6]
Output: false
# 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:
pre=-float('inf')
stack=[(1,root)]
while stack:
p=stack.pop()
if not p[1]:
continue
if p[0]==0:
if p[1].val<=pre:
return False
pre=p[1].val
else:
stack.append((1,p[1].right))
stack.append((0,p[1]))
stack.append((1,p[1].left))
return True