[Leetcode]Validate Binary Search Tree,leetcodevalidate
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.
檢查一棵樹是不是平衡二叉樹。上邊列出了BST的性質。開始寫了一個遞迴的方法,結果問題出在了INT_MAX和INT_MIN這兩個值上,如果這兩個值出現在樹中,這個方法就不可行了。
class Solution {public:bool isValidBST(TreeNode *root) {return check(root, INT_MAX, INT_MIN);}bool check(TreeNode *root, int max, int min){if (NULL == root) return true;if (root->val > min && root->val < max){return check(root->left, root->val, min) && check(root->right, max, root->val);}else return false;}};
在網上翻了好久,發現很多之前AC的代碼都是這麼寫的,說明leetcode有可能更新了test cases,加上了對INT_MAX和INT_MIN的檢測,使這些代碼沒辦法再AC了(就像reverse integar那道題一樣)。這種思路時間複雜度是O(n),空間複雜度是O(0)。
這樣的話,這種思路就行不通了。只能從BST的另一個性質出發,中序遍曆這棵樹,如果這棵樹是BST,那麼這個遍曆結果正好的升序排列的,這樣做空間複雜度也到達了O(n)。
class Solution {public:bool isValidBST(TreeNode *root) {vector<int> result;inorder(root, result);for (int i = 1; i < result.size(); i++){if (result[i - 1] >= result[i]) return false;}return true;}void inorder(TreeNode *root,vector<int> &result){if (!root) return;if (root->left) inorder(root->left, result);result.push_back(root->val);if (root->right) inorder(root->right, result);}};