Validate Binary Search Tree
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 | # Definition for a binary tree node. |
2. DFS & Inorder(中序遍历)
首先对二叉树进行中序遍历,然后对遍历的结果判断是否是一个完全递增的序列(不可相等),具体实现方法如下:
1 | # Definition for a binary tree node. |