【LeetCode OJ】Validate Binary Search Tree

Problem Link:

https://oj.leetcode.com/problems/validate-binary-search-tree/

We inorder-traverse the tree, and for each node we check if current_node.val > prev_node.val. The code is as follows.

# Definition for a  binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution:
# @param root, a tree node
# @return a boolean
def isValidBST(self, root):
stack = []
prev_node = None
p = root
while stack or p:
if p:
stack.append(p)
p = p.left
else:
p = stack.pop()
if prev_node:
if prev_node.val >= p.val:
return False
prev_node = p
p = p.right
return True
上一篇:LeetCode OJ:Validate Binary Search Tree(合法的二叉搜索树)


下一篇:LeetCode OJ 98. Validate Binary Search Tree