Skip to content

Commit 9881610

Browse files
committed
Solution of Leetcode Problem: 98 codeharborhub#872
1 parent 771d6ef commit 9881610

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
---
2+
id: validate binary search tree
3+
title: Validate Binary Search Tree
4+
sidebar_label: 0098 Validate Binary Search Tree
5+
tags:
6+
- tree
7+
- tree traversal
8+
- LeetCode
9+
- C++
10+
description: "This is a solution to the Validate Binary Search Tree problem on LeetCode."
11+
---
12+
13+
## Problem Description
14+
15+
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
16+
17+
A valid BST is defined as follows:
18+
19+
* The left subtree of a node contains only nodes with keys less than the node's key.
20+
* The right subtree of a node contains only nodes with keys greater than the node's key.
21+
* Both the left and right subtrees must also be binary search trees.
22+
23+
### Examples
24+
25+
**Example 1:**
26+
27+
```
28+
29+
Input: root = [2,1,3]
30+
Output: true
31+
```
32+
33+
**Example 2:**
34+
35+
```
36+
Input: root = [5,1,4,null,null,3,6]
37+
Output: false
38+
```
39+
40+
### Constraints
41+
42+
- The number of nodes in the tree is in the range $[1, 10^4]$.
43+
- -2^(31) <= Node.val <= 2^(31) - 1.
44+
45+
### Approach
46+
47+
To solve this problem(valid BST) we will do the inorder traversal of the tree as we know in a binary search tree the array of elements which we get after inorder traversal they will be in sorted order so after the inorder traversal we will just have check if the inorder traversal of the given binary search is in sorted order or not.
48+
49+
#### Code in C++
50+
51+
```cpp
52+
/**
53+
* Definition for a binary tree node.
54+
* struct TreeNode {
55+
* int val;
56+
* TreeNode *left;
57+
* TreeNode *right;
58+
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
59+
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
60+
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
61+
* right(right) {}
62+
* };
63+
*/
64+
class Solution {
65+
public:
66+
// Function for inorder traversal
67+
void inorder(TreeNode* root , vector<int>&a){
68+
if(root==NULL){
69+
return;
70+
}
71+
inorder(root->left,a);
72+
a.push_back(root->val);
73+
inorder(root->right,a);
74+
}
75+
bool isValidBST(TreeNode* root) {
76+
vector<int>a,b;
77+
inorder(root,a);
78+
b=a;
79+
for(int i=1;i<a.size();i++){
80+
if(a[i]==a[i-1]){ // it helps us to check that elements in given tree is not equal for valid BST
81+
return false;
82+
}
83+
}
84+
sort(b.begin(),b.end());
85+
for(int i=0;i<b.size();i++){
86+
if(b[i]!=a[i]){
87+
return false;
88+
}
89+
}
90+
return true;
91+
}
92+
};
93+
```
94+
95+

0 commit comments

Comments
 (0)