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:
1 | Input: |
Example 2:
1 | 5 |
解法
这题最开始我想得简单了,直接递归解,比较当前点与左右节点是否符合,然后递归左右节点。
代码如下:
1 | class Solution { |
显然,这种做法是错误的,考虑如下情况:
1 | 10 |
它并不是一棵合法的二叉搜索树,上面的算法会误判。
所以,采用两个变量记录当前节点可能的最大最小值,在每次判断时与这两个值比较即可。
具体代码如下:
1 | class Solution { |