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 root node's value is 5 but its right child's value is 4.
[1, 10^4].-2^31 <= Node.val <= 2^31 - 1No developer has claimed the Python throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
For a binary search tree, what if we traverse the tree inorder?
# 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 | None) -> bool:
# For a binary search tree, what if we traverse the tree inorder?
self.is_valid = True
self.pre_val = None
self.dfs(root)
return self.is_valid
def dfs(self, node):
if not self.is_valid:
return
if node is None:
return
self.dfs(node.left)
if self.pre_val is not None and self.pre_val >= node.val:
self.is_valid = False
return
self.pre_val = node.val
self.dfs(node.right)
No developer has claimed the Java throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the C++ throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the Javascript throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the Go throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the Rust throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the C# throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the Ruby throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the Swift throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.
No developer has claimed the Kotlin throne for LeetCode #98 yet. Submit an optimal idiomatic solution to become the reigning king and display your portfolio dofollow backlink to visiting engineers worldwide.