|
| 1 | +--- |
| 2 | +id: verify-preorder-sequence-in-binary-search-tree |
| 3 | +title: Verify Preorder Sequence in Binary Search Tree |
| 4 | +sidebar_label: 0255-Verify Preorder Sequence in Binary Search Tree |
| 5 | +tags: [Hash Map, Two Pointers,Binary Search Tree] |
| 6 | +description: Solution to finding and Verify Preorder Sequence in Binary Search Tree. |
| 7 | +--- |
| 8 | + |
| 9 | +### Description |
| 10 | + |
| 11 | +Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree. |
| 12 | + |
| 13 | +You may assume each number in the sequence is unique. |
| 14 | + |
| 15 | +Consider the following binary search tree: |
| 16 | + |
| 17 | +```bash |
| 18 | + 5 |
| 19 | + / \ |
| 20 | + 2 6 |
| 21 | + / \ |
| 22 | + 1 3 |
| 23 | +``` |
| 24 | + |
| 25 | +### Example: |
| 26 | + |
| 27 | +**Example 1:** |
| 28 | +```bash |
| 29 | +Input: [5,2,6,1,3] |
| 30 | +Output: false |
| 31 | +``` |
| 32 | + |
| 33 | + |
| 34 | +**Example 2:** |
| 35 | +```bash |
| 36 | +Input: [5,2,1,3,6] |
| 37 | +Output: true |
| 38 | +``` |
| 39 | +### Solution |
| 40 | + |
| 41 | +#### **Approach** |
| 42 | + |
| 43 | +- Use a stack to simulate the traversal. |
| 44 | +- Maintain a variable `low` which represents the lowest value that the next node can take. Initially, set `low` to negative infinity. |
| 45 | +- Iterate through the array: |
| 46 | + - If we encounter a value less than `low`, it means the sequence is invalid. |
| 47 | + - If the current value is greater than the top of the stack, keep popping from the stack and update `low` to the value of the last popped element. This ensures that we are correctly moving to the right subtree. |
| 48 | + - Push the current value onto the stack. |
| 49 | + |
| 50 | +<Tabs> |
| 51 | + |
| 52 | +<TabItem value="javascript" label="JavaScript"> |
| 53 | + |
| 54 | + |
| 55 | +```javascript |
| 56 | +function verifyPreorder(preorder) { |
| 57 | + let stack = []; |
| 58 | + let low = -Infinity; |
| 59 | + |
| 60 | + for (let value of preorder) { |
| 61 | + if (value < low) { |
| 62 | + return false; |
| 63 | + } |
| 64 | + while (stack.length > 0 && value > stack[stack.length - 1]) { |
| 65 | + low = stack.pop(); |
| 66 | + } |
| 67 | + stack.push(value); |
| 68 | + } |
| 69 | + return true; |
| 70 | +} |
| 71 | + |
| 72 | +// Example usage: |
| 73 | +const preorder1 = [5, 2, 6, 1, 3]; |
| 74 | +console.log(verifyPreorder(preorder1)); // Output: false |
| 75 | + |
| 76 | +const preorder2 = [5, 2, 1, 3, 6]; |
| 77 | +console.log(verifyPreorder(preorder2)); // Output: true |
| 78 | +``` |
| 79 | + |
| 80 | +</TabItem> |
| 81 | + |
| 82 | +<TabItem value="typescript" label="TypeScript"> |
| 83 | + |
| 84 | + |
| 85 | +```typescript |
| 86 | +function verifyPreorder(preorder: number[]): boolean { |
| 87 | + let stack: number[] = []; |
| 88 | + let low: number = -Infinity; |
| 89 | + |
| 90 | + for (let value of preorder) { |
| 91 | + if (value < low) { |
| 92 | + return false; |
| 93 | + } |
| 94 | + while (stack.length > 0 && value > stack[stack.length - 1]) { |
| 95 | + low = stack.pop()!; |
| 96 | + } |
| 97 | + stack.push(value); |
| 98 | + } |
| 99 | + return true; |
| 100 | +} |
| 101 | + |
| 102 | +// Example usage: |
| 103 | +const preorder1: number[] = [5, 2, 6, 1, 3]; |
| 104 | +console.log(verifyPreorder(preorder1)); // Output: false |
| 105 | + |
| 106 | +const preorder2: number[] = [5, 2, 1, 3, 6]; |
| 107 | +console.log(verifyPreorder(preorder2)); // Output: true |
| 108 | +``` |
| 109 | + |
| 110 | +</TabItem> |
| 111 | + |
| 112 | +<TabItem value="python" label="Python"> |
| 113 | + |
| 114 | + |
| 115 | +```python |
| 116 | +def verifyPreorder(preorder): |
| 117 | + stack = [] |
| 118 | + low = float('-inf') |
| 119 | + |
| 120 | + for value in preorder: |
| 121 | + if value < low: |
| 122 | + return False |
| 123 | + while stack and value > stack[-1]: |
| 124 | + low = stack.pop() |
| 125 | + stack.append(value) |
| 126 | + |
| 127 | + return True |
| 128 | + |
| 129 | +# Example usage: |
| 130 | +preorder1 = [5, 2, 6, 1, 3] |
| 131 | +print(verifyPreorder(preorder1)) # Output: False |
| 132 | + |
| 133 | +preorder2 = [5, 2, 1, 3, 6] |
| 134 | +print(verifyPreorder(preorder2)) # Output: True |
| 135 | +``` |
| 136 | + |
| 137 | +</TabItem> |
| 138 | + |
| 139 | +<TabItem value="java" label="Java"> |
| 140 | + |
| 141 | +```java |
| 142 | +import java.util.Stack; |
| 143 | + |
| 144 | +public class Solution { |
| 145 | + public boolean verifyPreorder(int[] preorder) { |
| 146 | + Stack<Integer> stack = new Stack<>(); |
| 147 | + int low = Integer.MIN_VALUE; |
| 148 | + |
| 149 | + for (int value : preorder) { |
| 150 | + if (value < low) { |
| 151 | + return false; |
| 152 | + } |
| 153 | + while (!stack.isEmpty() && value > stack.peek()) { |
| 154 | + low = stack.pop(); |
| 155 | + } |
| 156 | + stack.push(value); |
| 157 | + } |
| 158 | + return true; |
| 159 | + } |
| 160 | + |
| 161 | + public static void main(String[] args) { |
| 162 | + Solution solution = new Solution(); |
| 163 | + |
| 164 | + int[] preorder1 = {5, 2, 6, 1, 3}; |
| 165 | + System.out.println(solution.verifyPreorder(preorder1)); // Output: false |
| 166 | + |
| 167 | + int[] preorder2 = {5, 2, 1, 3, 6}; |
| 168 | + System.out.println(solution.verifyPreorder(preorder2)); // Output: true |
| 169 | + } |
| 170 | +} |
| 171 | +``` |
| 172 | +</TabItem> |
| 173 | +<TabItem value="cpp" label="C++"> |
| 174 | + |
| 175 | + |
| 176 | +```cpp |
| 177 | +#include <iostream> |
| 178 | +#include <vector> |
| 179 | +#include <stack> |
| 180 | +#include <limits.h> |
| 181 | + |
| 182 | +using namespace std; |
| 183 | + |
| 184 | +class Solution { |
| 185 | +public: |
| 186 | + bool verifyPreorder(vector<int>& preorder) { |
| 187 | + stack<int> stk; |
| 188 | + int low = INT_MIN; |
| 189 | + |
| 190 | + for (int value : preorder) { |
| 191 | + if (value < low) { |
| 192 | + return false; |
| 193 | + } |
| 194 | + while (!stk.empty() && value > stk.top()) { |
| 195 | + low = stk.top(); |
| 196 | + stk.pop(); |
| 197 | + } |
| 198 | + stk.push(value); |
| 199 | + } |
| 200 | + |
| 201 | + return true; |
| 202 | + } |
| 203 | +}; |
| 204 | + |
| 205 | +int main() { |
| 206 | + Solution solution; |
| 207 | + |
| 208 | + vector<int> preorder1 = {5, 2, 6, 1, 3}; |
| 209 | + cout << (solution.verifyPreorder(preorder1) ? "true" : "false") << endl; // Output: false |
| 210 | + |
| 211 | + vector<int> preorder2 = {5, 2, 1, 3, 6}; |
| 212 | + cout << (solution.verifyPreorder(preorder2) ? "true" : "false") << endl; // Output: true |
| 213 | + |
| 214 | + return 0; |
| 215 | +} |
| 216 | +``` |
| 217 | + |
| 218 | + |
| 219 | +</TabItem> |
| 220 | +</Tabs> |
| 221 | + |
| 222 | +### Explanation: |
| 223 | + |
| 224 | + |
| 225 | +<Tabs> |
| 226 | + |
| 227 | +<TabItem value="javascript" label="JavaScript"> |
| 228 | + |
| 229 | +1. **Initialization**: |
| 230 | + - A stack is used to keep track of the nodes. |
| 231 | + - `low` is initialized to `-Infinity` to represent the smallest possible value initially. |
| 232 | + |
| 233 | +2. **Iteration**: |
| 234 | + - For each value in the `preorder` array: |
| 235 | + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `false`. |
| 236 | + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. |
| 237 | + - Push the current value onto the stack. |
| 238 | + |
| 239 | +3. **Return**: |
| 240 | + - If we successfully iterate through the entire array without finding any violations, return `true`. |
| 241 | + |
| 242 | +</TabItem> |
| 243 | + |
| 244 | +<TabItem value="typescript" label="TypeScript"> |
| 245 | + |
| 246 | + |
| 247 | +1. **Initialization**: |
| 248 | + - A stack is used to keep track of the nodes. |
| 249 | + - `low` is initialized to `-Infinity` to represent the smallest possible value initially. |
| 250 | + |
| 251 | +2. **Iteration**: |
| 252 | + - For each value in the `preorder` array: |
| 253 | + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `false`. |
| 254 | + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. |
| 255 | + - Push the current value onto the stack. |
| 256 | + |
| 257 | +3. **Return**: |
| 258 | + - If we successfully iterate through the entire array without finding any violations, return `true`. |
| 259 | + |
| 260 | +</TabItem> |
| 261 | + |
| 262 | +<TabItem value="python" label="Python"> |
| 263 | + |
| 264 | +1. **Initialization**: |
| 265 | + - A stack is used to keep track of the nodes. |
| 266 | + - `low` is initialized to negative infinity to represent the smallest possible value initially. |
| 267 | + |
| 268 | +2. **Iteration**: |
| 269 | + - For each value in the `preorder` array: |
| 270 | + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `False`. |
| 271 | + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. |
| 272 | + - Push the current value onto the stack. |
| 273 | + |
| 274 | +3. **Return**: |
| 275 | + - If we successfully iterate through the entire array without finding any violations, return `True`. |
| 276 | + |
| 277 | +</TabItem> |
| 278 | + |
| 279 | +<TabItem value="java" label="Java"> |
| 280 | + |
| 281 | +1. **Initialization**: |
| 282 | + - A stack is used to keep track of the nodes. |
| 283 | + - `low` is initialized to `Integer.MIN_VALUE` to represent the smallest possible value initially. |
| 284 | + |
| 285 | +2. **Iteration**: |
| 286 | + - For each value in the `preorder` array: |
| 287 | + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `false`. |
| 288 | + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. |
| 289 | + - Push the current value onto the stack. |
| 290 | + |
| 291 | +3. **Return**: |
| 292 | + - If we successfully iterate through the entire array without finding any violations, return `true`. |
| 293 | + |
| 294 | +</TabItem> |
| 295 | + |
| 296 | +<TabItem value="cpp" label="C++"> |
| 297 | + |
| 298 | +1. **Initialization**: |
| 299 | + - A stack is used to keep track of the nodes. |
| 300 | + - `low` is initialized to `INT_MIN` to represent the smallest possible value initially. |
| 301 | + |
| 302 | +2. **Iteration**: |
| 303 | + - For each value in the `preorder` array: |
| 304 | + - If the value is less than `low`, it means we are visiting a node in the right subtree that violates the BST property, hence return `false`. |
| 305 | + - If the current value is greater than the top of the stack, it means we are transitioning from the left subtree to the right subtree. We keep popping the stack and update `low` to ensure that subsequent nodes in the right subtree are greater than this value. |
| 306 | + - Push the current value onto the stack. |
| 307 | + |
| 308 | +3. **Return**: |
| 309 | + - If we successfully iterate through the entire array without finding any violations, return `true`. |
| 310 | + |
| 311 | +</TabItem> |
| 312 | + |
| 313 | +</Tabs> |
| 314 | + |
| 315 | +### Complexity: |
| 316 | + |
| 317 | + |
| 318 | +<Tabs> |
| 319 | +<TabItem value="javascript" label="JavaScript"> |
| 320 | + |
| 321 | + |
| 322 | +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. |
| 323 | +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. |
| 324 | + |
| 325 | +</TabItem> |
| 326 | +<TabItem value="typescript" label="TypeScript"> |
| 327 | + |
| 328 | + |
| 329 | +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. |
| 330 | +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. |
| 331 | + |
| 332 | +</TabItem> |
| 333 | + |
| 334 | +<TabItem value="python" label="Python"> |
| 335 | + |
| 336 | + |
| 337 | +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. |
| 338 | +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. |
| 339 | + |
| 340 | +</TabItem> |
| 341 | + |
| 342 | +<TabItem value="java" label="Java"> |
| 343 | + |
| 344 | +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. |
| 345 | +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. |
| 346 | +</TabItem> |
| 347 | +<TabItem value="cpp" label="c++"> |
| 348 | + |
| 349 | +- **Time Complexity**: `O(n)`, where `n` is the length of the preorder array. Each element is pushed and popped from the stack at most once. |
| 350 | +- **Space Complexity**: `O(n)`, where `n` is the length of the preorder array, which is the worst-case space complexity for the stack. |
| 351 | + |
| 352 | +</TabItem> |
| 353 | +</Tabs> |
| 354 | + |
| 355 | + |
| 356 | + |
| 357 | +## References |
| 358 | + |
| 359 | +- **LeetCode Problem:** [Binary Search Tree](https://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/) |
| 360 | + |
| 361 | +<h2>Author:</h2> |
| 362 | + |
| 363 | +<div style={{display: 'flex', flexWrap: 'wrap', justifyContent: 'space-between', gap: '10px'}}> |
| 364 | +{['sivaprasath2004'].map(username => ( |
| 365 | + <Author key={username} username={username} /> |
| 366 | +))} |
| 367 | +</div> |
0 commit comments