|
| 1 | +# [Validate Binary Search Tree](https://leetcode.com/problems/validate-binary-search-tree/description/) |
| 2 | + |
| 3 | +## Intuition |
| 4 | + |
| 5 | +To validate whether a binary tree is a binary search tree (BST), we need to ensure that each node satisfies the BST |
| 6 | +property: |
| 7 | + |
| 8 | +1. The left subtree of a node contains only nodes with keys less than the node’s key. |
| 9 | +2. The right subtree of a node contains only nodes with keys greater than the node’s key. |
| 10 | + |
| 11 | +The problem can be approached using a breadth-first search (BFS), where each node is checked against the valid range of |
| 12 | +values it can have, derived from its parent nodes. |
| 13 | + |
| 14 | +## Approach |
| 15 | + |
| 16 | +1. **Breadth-First Search (BFS):** |
| 17 | + - Use a queue to traverse the tree level by level. |
| 18 | + - Each element in the queue is a tuple (`Tuple3<TreeNode, Long, Long>`) that contains: |
| 19 | + - The current node. |
| 20 | + - The valid minimum (`min`) value the node can have. |
| 21 | + - The valid maximum (`max`) value the node can have. |
| 22 | + - For each node, check whether its value lies within the valid range: |
| 23 | + - If `node.value` is not within `[min, max]`, the tree is invalid, so return `false`. |
| 24 | + - Otherwise, update the range for the left and right children: |
| 25 | + - Left child: `max` becomes the value of the current node. |
| 26 | + - Right child: `min` becomes the value of the current node. |
| 27 | +2. **Return True for a Valid BST:** If the queue becomes empty without finding any violations of the BST property, |
| 28 | + return `true`. |
| 29 | + |
| 30 | +## Complexity |
| 31 | + |
| 32 | +- **Time Complexity: `O(n)`**, where `n` is the number of nodes in the tree. Each node is processed once. |
| 33 | +- **Space Complexity: `O(n)`**, for the queue, which may contain up to `n` nodes in the worst case (e.g., a complete |
| 34 | + binary tree). |
| 35 | + |
| 36 | +## Code |
| 37 | + |
| 38 | +- [Java](../src/main/java/io/dksifoua/leetcode/validatebinarysearchtree/Solution.java) |
| 39 | + |
| 40 | +## Summary |
| 41 | + |
| 42 | +This BFS solution ensures each node is validated against the BST property by maintaining a valid range for its values, |
| 43 | +derived from its parent nodes. The use of a queue and tuples makes the implementation clear and avoids recursion stack |
| 44 | +overhead, providing an efficient `O(n)` time complexity. |
0 commit comments