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.
1public class TreeNode {
2 public int val;
3 public TreeNode left;
4 public TreeNode right;
5 public TreeNode(int x) { val = x; }
6}
7
8public class Solution {
9 public bool IsValidBST(TreeNode root) {
10 return Validate(root, long.MinValue, long.MaxValue);
11 }
12
13 private bool Validate(TreeNode node, long min, long max) {
14 if (node == null) return true;
15 if (node.val <= min || node.val >= max) return false;
16 return Validate(node.left, min, node.val) && Validate(node.right, node.val, max);
17 }
18}
The Validate
method checks if each subtree is a valid BST by maintaining a dynamic range of minimum and maximum allowable values for nodes.
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.
1class TreeNode:
2 def __init__(self, val=0, left=None, right=None):
3 self.val = val
4 self.left = left
5 self.right = right
6
7class Solution:
8 def isValidBST(self, root: TreeNode) -> bool:
9 stack = []
10 current = root
11 prevVal = -float('inf')
12
13 while stack or current:
14 while current:
15 stack.append(current)
16 current = current.left
17 current = stack.pop()
18 if current.val <= prevVal:
19 return False
20 prevVal = current.val
21 current = current.right
22
23 return True
This Python solution uses a list as a stack to conduct iterative in-order traversal. It checks each node's value against the last visited to determine BST validity.