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.
1 | Example 1: |
1 | 利用BST树的特性,从上往下递归,记录min_node和max_node,对左子树来说,只需记录max_node,即它的父节点;同理对于右字数,只需记录min_node。然后它们满足BST关系即可。 |
1 | 利用中序遍历关系。由于BST树的中序遍历是有序的,所以我们用中序遍历来做文章。 |