題目難度: 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();
}