LeetCode Validate Binary Search Tree
LeetCode-based Validate Binary Search Tree
Original question
Determine whether a binary search tree is valid. Effective means that each node has a value greater than or equal to the left node (if there is a corresponding node), and its left and right nodes also meet this condition.
Note:
None
Example:
Input:
2 / \1 3
Output: True
Solutions
The Binary Tree Inorder Traversal is modified. In the middle-order traversal of the tree, the node sequence is left node, root node, and right node. This means that when a binary search tree meets the requirements, its ordinal traversal sequence must increase progressively. If the preceding node is larger than the following node in the middle-order traversal, it indicates that it does not meet the requirements.
AC Source Code
# Definition for a binary tree node.class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = Noneclass Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ stack = [] curr = root prev = None while curr or stack: while curr: stack.append(curr) curr = curr.left if stack: curr = stack.pop() if prev and curr.val <= prev.val: return False prev = curr curr = curr.right return Trueif __name__ == "__main__": None