一. 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:
2
/ \
1 3
Binary tree [2,1,3], return true.
Example 2:
1
/ \
2 3
Binary tree [1,2,3], return false.
Difficulty:Medium
TIME:8MIN
解法(中序遍歷)
如何判斷一個二叉查找樹是否是有效的呢,如果判斷每個結點的左子節點和右子節點是否有效,那就是有點片面。
其實觀察二叉查找樹的構造方式,可以發現,二叉查找樹的左子節點肯定小於根節點,而根節點肯定小於右子節點,也就是:
左<中<右
而這正是中序遍歷的順序,因此,如果採用中序遍歷二叉查找樹,那麼得到的應當是一個單調遞增序列。如果序列不是單調遞增的,說明這個二叉查找樹不是有效的二叉查找樹。
TreeNode *prev = NULL;
bool dfs(TreeNode* root) {
if(root == NULL)
return true;
if(!dfs(root->left))
return false;
if(prev != NULL && prev->val >= root->val) //如果不是單調遞增序列,說明不是有效的BST
return false;
prev = root;
return dfs(root->right);
}
bool isValidBST(TreeNode* root) {
return dfs(root);
}
代碼的時間複雜度爲