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