标签:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
Analyse:
1. Using upper bound(INT_MAX) and lower bound(INT_MIN).
NA: Because if the root is INT_MAX / INT_MIN, it will cause error.
There is a chancy method: we can set the upper bound higher and the lower bound smaller. And let the arguments be long long int type.
Runtime: 12ms.
2. Use inorder traversal to get the inorder sequence, then check whether it‘s ascending.
Runtime: 16ms.
1 /**
2 * Definition for a binary tree node.
3 * struct TreeNode {
4 * int val;
5 * TreeNode *left;
6 * TreeNode *right;
7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8 * };
9 */
10 class Solution {
11 public:
12 bool isValidBST(TreeNode* root) {
13 if(!root) return true;
14
15 vector<int> result;
16 inorder(root, result);
17 for(int i = 1; i < result.size(); i++){
18 if(result[i] <= result[i - 1]) return false;
19 }
20 return true;
21 }
22 void inorder(TreeNode* root, vector<int>& result){
23 if(root->left) inorder(root->left, result);
24 result.push_back(root->val);
25 if(root->right) inorder(root->right, result);
26 }
27 };
3. For every node, check its left subtree nodes whether are all smaller than it and check its right subtree nodes whether are all larger than it.
Runtime: 20ms.
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 bool isValidBST(TreeNode* root) { 13 if(!root) return true; 14 if(!root->left && !root->right) return true; 15 16 if(validLeft(root->left, root->val) && validRight(root->right, root->val)){ 17 return isValidBST(root->left) && isValidBST(root->right); 18 } 19 else return false; 20 } 21 bool validLeft(TreeNode* root, int max){ 22 if(!root) return true; 23 if(root->val >= max) return false; 24 return validLeft(root->left, max) && 25 validLeft(root->right, max); //make sure every node in left subtree is smaller than the root value 26 } 27 bool validRight(TreeNode* root, int min){ 28 if(!root) return true; 29 if(root->val <= min) return false; 30 return validRight(root->left, min) && 31 validRight(root->right, min); //make sure every node in the right subtree is larger than the root value 32 } 33 };
标签:
原文地址:http://www.cnblogs.com/amazingzoe/p/4688681.html