Valid Binary Search Tree
Last updated
Last updated
Given the root
of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Let's analyze the time and space complexity of the given algorithm:
Time Complexity: The time complexity of this algorithm is O(n), where n is the number of nodes in the binary tree. This is because in the worst case, the algorithm needs to visit all the nodes of the tree to check if it's a valid BST.
Space Complexity: The space complexity of this algorithm is O(h), where h is the height of the binary tree. This is because the maximum amount of space used by the call stack during the recursive calls is equal to the height of the tree. In the worst case, when the tree is skewed, the height of the tree is equal to the number of nodes, so the space complexity would be O(n).