c_cpp 验证二进制搜索Treehttp://oj.leetcode.com/problems/validate-binary-search-tree/
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp 验证二进制搜索Treehttp://oj.leetcode.com/problems/validate-binary-search-tree/相关的知识,希望对你有一定的参考价值。
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isValidBST(TreeNode *root) {
if(root == NULL){
return true;
}
else if(!postVisitBST(root).empty()){
return true;
}
else{
return false;
}
}
//return empty vector if it is not BST, and root should not be NULL
vector<int> postVisitBST(TreeNode *root){
vector<int> result;
if(root == NULL){
//This should not happen!!
return result;
}
else if(root->left == NULL && root->right == NULL){
result.push_back(root->val);
result.push_back(root->val);
return result;
}
else if(root->left == NULL){
vector<int> t_right = postVisitBST(root->right);
if(t_right.empty()){
return result;
}
if(t_right[0] > root->val){
result.push_back(root->val);
result.push_back(t_right[1]);
return result;
}
else{
return result;
}
}
else if(root->right == NULL){
vector<int> t_left = postVisitBST(root->left);
if(t_left.empty()){
return result;
}
if(t_left[1] < root->val){
result.push_back(t_left[0]);
result.push_back(root->val);
return result;
}
else{
return result;
}
}
else{
vector<int> t_left = postVisitBST(root->left);
vector<int> t_right = postVisitBST(root->right);
if(t_left.empty() || t_right.empty()){
return result;
}
if(t_left[1] < root->val && t_right[0] > root->val){
result.push_back(t_left[0]);
result.push_back(t_right[1]);
return result;
}
else{
return result;
}
}
}
};
以上是关于c_cpp 验证二进制搜索Treehttp://oj.leetcode.com/problems/validate-binary-search-tree/的主要内容,如果未能解决你的问题,请参考以下文章
c_cpp Binary Treehttp的最小深度://oj.leetcode.com/problems/minimum-depth-of-binary-tree/
c_cpp 98.验证二进制搜索树
c_cpp 700.在二进制搜索树中搜索
c_cpp 二进制搜索
c_cpp 二进制搜索
c_cpp 二进制搜索