This approach involves recursively traversing the binary tree in an in-order manner, comparing each node's value with a running minimum and maximum valid value, to ensure the BST properties hold. The initial minimum and maximum allow for any integer value, and they get updated as we traverse the tree.
Time Complexity: O(n), where n is the number of nodes because we visit each node exactly once.
Space Complexity: O(h), where h is the height of the tree due to the recursive stack usage.
1function TreeNode(val, left = null, right = null) {
2 this.val = (val===undefined ? 0 : val);
3 this.left = (left===undefined ? null : left);
4 this.right = (right===undefined ? null : right);
5}
6
7var isValidBST = function(root) {
8 const validate = (node, min, max) => {
9 if (!node) return true;
10 if (node.val <= min || node.val >= max) return false;
11 return validate(node.left, min, node.val) &&
12 validate(node.right, node.val, max);
13 };
14 return validate(root, -Infinity, Infinity);
15};
This solution uses a helper function to traverse and check the BST conditions by ensuring each node falls within the valid integer range based on its position in the tree.
This approach involves an iterative in-order traversal using a stack to ensure non-decreasing order of node values. We iterate through the nodes using the stack and at each step, compare the current node's value with the last visited node.
Time Complexity: O(n) since each node is visited once.
Space Complexity: O(h) for the stack where h is tree height.
1import java.util.Stack;
2
3class TreeNode {
4 int val;
5 TreeNode left;
6 TreeNode right;
7 TreeNode(int x) { val = x; }
8}
9
10class Solution {
11 public boolean isValidBST(TreeNode root) {
12 Stack<TreeNode> stack = new Stack<>();
13 TreeNode current = root;
14 long prevVal = Long.MIN_VALUE;
15
16 while (!stack.isEmpty() || current != null) {
17 while (current != null) {
18 stack.push(current);
19 current = current.left;
20 }
21 current = stack.pop();
22 if (current.val <= prevVal)
23 return false;
24 prevVal = current.val;
25 current = current.right;
26 }
27 return true;
28 }
29}
Java's Stack
is used for iterative in-order tree traversal. The solution checks during traversal to ensure each node has a greater value than its predecessor.