Solve leetcode 98
- User
Solve leetcode 98
- Assistant
Solve leetcode 98
Certainly! LeetCode Problem 98: Validate Binary Search Tree is a classic algorithmic challenge that tests your understanding of binary search trees (BSTs) and tree traversal techniques. Below, I'll provide a comprehensive solution, including multiple approaches, detailed explanations, and Python code examples to help you understand how to tackle this problem effectively.
Validate Binary Search Tree
Given the root of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
Example 1:
2
/ \
1 3
Input: root = [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: root = [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
Overview:
In a BST, an in-order traversal (left, root, right) should yield a sorted list of values in ascending order. We can perform an in-order traversal and verify that each subsequent value is greater than the previous one.
Steps:
Time Complexity: O(n), where n is the number of nodes.
Space Complexity: O(h), where h is the height of the tree (due to the recursion stack).
Python Code:
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
self.prev = None # Initialize previous node as None
def in_order(node):
if not node:
return True
# Traverse left subtree
if not in_order(node.left):
return False
# Visit current node
if self.prev is not None and node.val <= self.prev:
return False
self.prev = node.val
# Traverse right subtree
return in_order(node.right)
return in_order(root)
Explanation:
in_order to perform the traversal.self.prev keeps track of the value of the previously visited node.self.prev, we return False.True.Overview:
Another approach is to recursively validate that each node's value falls within a specific range (min and max). Initially, the range is set to negative and positive infinity. As we traverse the tree:
Steps:
Time Complexity: O(n), where n is the number of nodes.
Space Complexity: O(h), where h is the height of the tree (due to the recursion stack).
Python Code:
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
def validate(node, low, high):
if not node:
return True
# The current node's value must be greater than low and less than high
if not (low < node.val < high):
return False
# Recursively validate the left and right subtrees with updated bounds
return (validate(node.left, low, node.val) and
validate(node.right, node.val, high))
return validate(root, float('-inf'), float('inf'))
Explanation:
validate function checks whether the current node's value is within the specified low and high bounds.high bound is updated to the current node's value.low bound is updated to the current node's value.False.Overview:
Instead of using recursion, we can perform an in-order traversal iteratively using a stack. This approach can be more space-efficient in practice and avoids potential stack overflow issues with deep trees.
Steps:
False.True.Time Complexity: O(n), where n is the number of nodes.
Space Complexity: O(h), where h is the height of the tree (due to the stack).
Python Code:
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
stack = []
prev = None
current = root
while stack or current:
# Reach the leftmost node of the current node
while current:
stack.append(current)
current = current.left
# Current must be None at this point
current = stack.pop()
# Check if the current node's value is greater than the previous value
if prev is not None and current.val <= prev:
return False
prev = current.val
# Visit the right subtree
current = current.right
return True
Explanation:
prev stores the value of the previously visited node.prev.All three approaches have the same time complexity of O(n) and space complexity of O(h), where h is the height of the tree. The choice between them depends on your preference and specific constraints:
Validating a Binary Search Tree involves ensuring that each node adheres to the BST properties relative to its position in the tree. Whether you choose a recursive in-order traversal, recursive validation with bounds, or an iterative approach, the key is to methodically verify the ordering of nodes.
I hope this comprehensive explanation helps you understand how to solve LeetCode Problem 98 effectively! If you have any further questions or need clarification on any part of the solution, feel free to ask.
Not yet included in a published release.