jayati

Validate Binary Search Tree using ignorer

Jan 31st, 2023
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.93 KB | None | 0 0
  1. /**
  2.  * Definition for a binary tree node.
  3.  * struct TreeNode {
  4.  *     int val;
  5.  *     TreeNode *left;
  6.  *     TreeNode *right;
  7.  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8.  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9.  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10.  * };
  11.  */
  12. class Solution {
  13.  
  14. void inordertraversal(TreeNode* root,vector<int> &ans)
  15. {
  16.     if(root==nullptr)
  17.     {
  18.         return;
  19.     }
  20.     inordertraversal(root->left,ans);
  21.     ans.push_back(root->val);
  22.     inordertraversal(root->right,ans);
  23.    
  24. }
  25. public:
  26.     bool isValidBST(TreeNode* root) {
  27.         vector<int> ans;
  28.        inordertraversal(root,ans);
  29.        
  30.        
  31.        for(int i=0;i<ans.size()-1;i++)
  32.        {
  33.            if(ans[i+1]<=ans[i])
  34.            {
  35.  
  36.                return false;
  37.            }
  38.        }
  39.        return true;
  40.        
  41.        
  42.     }
  43. };
Advertisement
Add Comment
Please, Sign In to add comment