Validate Binary Search Tree(cpp, leetcode,tree)

 Validate Binary Search Tree(cpp, leetcode,tree)

 Given a binary tree, determine if it is a valid binary search tree (BST).

Example 2:

    5
   / \
  1   4
     / \
    3   6


Output: false
Explanation: The root node's value is 5 but its right child's value is 4. 
-------------------------------------------------------------------------------
class Solution {
public:
bool isValidBST(TreeNode* root)
{
stack<TreeNode*>s;

vector<int>a;
if(root==NULL)
return true;

s.push(root);
root=root->left;
while(1)
{
while(root)
{
s.push(root);
root=root->left;
}
if(s.empty())
{
break;
}
root=s.top();
s.pop();
a.push_back(root->val);
root=root->right;


}

for(int i=0;i<a.size()-1;i++)
{
if(a[i]>=a[i+1])
return false;
}
return true;
}
};

 

Comments

Popular posts from this blog

Amazing Subarrays(cpp,interviewbit)

Symmetric Tree(leetcode,cpp):

sum of left leaves in a tree(leetcode).