98. Validate Binary Search Tree
problem description
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
Example 2:
algorithm thought
得到合法的BST,BST有个性质就是中序遍历结果是一个有序数组。所以我们直接中序遍历,每次保存前一个值,如果前一个值大于等于当前遍历的值,那么就不是一个合法的BST,否则就是合法的BST
code
algorithm analysis
时间复杂度O(n),遍历的时间,空间复杂度O(n),使用一个栈保存数据。其实可以用之前的Morris tarversal但是LeetCode可能是有bug,代码是正确的但是最后得不到合理的结果。
Last updated