标签:
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
[Solution]
1、递归
bool isValidBST(TreeNode *root) { return BSTCheck(root, (long long)INT_MIN - 1, (long long)INT_MAX + 1); } bool BSTCheck(TreeNode *root, long long left, long long right) { if (root == NULL) return true; return ((long long)root->val > left) && ((long long)root->val < right) && BSTCheck(root->left, left, root->val) && BSTCheck(root->right, root->val, right); }
2、根据BST的性质,中序遍历结果递增
1 bool isValidBST(TreeNode *root) 2 { 3 vector<int> vtree; 4 5 if (root == NULL) 6 return true; 7 8 inorder(root, vtree); 9 for (int i = 0; i < vtree.size() - 1; i++) 10 { 11 if (vtree[i] >= vtree[i + 1]) 12 return false; 13 } 14 return true; 15 } 16 17 void inorder(TreeNode *root, vector <int> &ret) 18 { 19 if (root == NULL) 20 return; 21 inorder(root->left, ret); 22 ret.push_back(root->val); 23 inorder(root->right, ret); 24 }
leetcode 98. Validate Binary Search Tree
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4295694.html