题目难度: Medium
原题描述:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
(1)The left subtree of a node contains only nodes with keys less than the node's key.
(2)The right subtree of a node contains only nodes with keys greater than the node's key.
(3)Both the left and right subtrees must also be binary search trees.
题目大意:
给你一棵二叉树,判断它是不是一棵二叉搜索树(二叉排序树)。
解题思路:
一开始没考虑周到,只是满足了左子节点比根节点小且右子节点比根节点大的条件,忽略了左子树全部节点比根节点小且右子树全部节点比根节点大的条件。后来又想得太复杂,在想如何得出左子树节点的最大值和右子树节点的最小值来跟根节点比较的问题,在想是不是要用dp记录一下。接着幸好想起了二叉排序树的一个重要性质:中序遍历一棵二叉排序树将得到一个递增的有序序列,因此我们只需要中序遍历一次,看它是不是递增有序就可以了。
时间复杂度分析:
dfs一棵二叉树的时间复杂度为O(V+E),又因为二叉树中V=E+1,因此时间复杂度为O(V)。在实现中我将按中序遍历的结果放在了一个数组里面,最后再检查这个数组是不是递增有序,这一步的时间复杂度为O(V)。因此总的时间复杂度为O(V)。
以下是代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define maxn 10000
int a[maxn];
int k;
void init(){
memset(a,0,sizeof(a));
k = 0;
}
void dfs(struct TreeNode* root){
if(root == NULL)
return;
dfs(root->left);
a[k++] = root->val;
dfs(root->right);
}
bool check(){
for(int i=0 ; i<k-1 ; ++i){
if(a[i]>=a[i+1])
return false;
}
return true;
}
bool isValidBST(struct TreeNode* root) {
init();
dfs(root);
return check();
}