题目链接: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.

confused what “{1,#,2,3}” means? > read more on how binary tree is serialized on OJ.

OJ’s Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where ‘#’ signifies a path terminator where no node exists below.

Here’s an example:

   1
  / \
 2   3
    /
   4
    \
     5

The above binary tree is serialized as “{1,2,3,#,#,4,#,#,5}”.

这道题的要求是检测二叉树是否为二叉搜索树(BST)。

二叉搜索树,顾名思义,它是一个二叉树,即每个节点下面最多有2个子节点。同时为了便于搜索的特性,二叉搜索树或者是一棵空树,或者是具有下列性质的二叉树:

  • 若其左子树不空,则左子树上所有结点的值均小于根结点的值;
  • 若其右子树不空,则右子树上所有结点的值均大于根结点的值;
  • 其左、右子树也分别为二叉搜索树。

二叉搜索树还有个特点就是中序遍历是严格递增的,因此可以利用个特性检查一个二叉树是否为二叉搜索树。采用pre变量记录前一节点,然后对二叉树进行中序遍历,同时检测pre节点的数字是否小于当前节点即可。

时间复杂度:O(n)

空间复杂度:O(1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution
{
public:
    bool isValidBST(TreeNode *root)
    {
        TreeNode *pre = NULL;
        inorderTraversal(root, pre);
    }
private:
    bool inorderTraversal(TreeNode *p, TreeNode *&pre)
    {
        if(p == NULL)
            return true;
        
        if(!inorderTraversal(p -> left, pre))
            return false;
        
        if(pre != NULL && pre -> val >= p -> val)
            return false;
        pre = p;
        
        if(!inorderTraversal(p -> right, pre))
            return false;
        
        return true;
    }
};