Skip to content

add algorithm to check binary search tree #7947

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 30 commits into from
Nov 3, 2022
Merged
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
e9f4b23
add algorithm to check binary search tree
alexpantyukhin Nov 2, 2022
e2693ee
add tests
alexpantyukhin Nov 2, 2022
948dc8b
add leetcode link
alexpantyukhin Nov 2, 2022
39ec691
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 2, 2022
068607d
fix typehints
alexpantyukhin Nov 2, 2022
c721ca3
typehints fixes
alexpantyukhin Nov 2, 2022
7c13235
Merge remote-tracking branch 'origin/is_binary_search_tree' into is_b…
alexpantyukhin Nov 2, 2022
7e76f52
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 2, 2022
c531f96
Update data_structures/binary_tree/is_bst.py
alexpantyukhin Nov 2, 2022
f821963
Update data_structures/binary_tree/is_bst.py
alexpantyukhin Nov 2, 2022
73769ae
Update data_structures/binary_tree/is_bst.py
alexpantyukhin Nov 2, 2022
dd0fbf8
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 2, 2022
6b3eac4
fix flake8
alexpantyukhin Nov 2, 2022
a58f63f
Merge branch 'is_binary_search_tree' of https://github.com/alexpantyu…
alexpantyukhin Nov 2, 2022
385a5ab
fix typehint
alexpantyukhin Nov 2, 2022
ef2e902
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 2, 2022
a467c1f
add TreeNode resolving
alexpantyukhin Nov 2, 2022
7cffe20
Update data_structures/binary_tree/is_bst.py
alexpantyukhin Nov 2, 2022
516cb2d
Update data_structures/binary_tree/is_bst.py
alexpantyukhin Nov 2, 2022
6ba1056
Update data_structures/binary_tree/is_bst.py
alexpantyukhin Nov 2, 2022
bdf43d4
Update data_structures/binary_tree/is_bst.py
alexpantyukhin Nov 2, 2022
c11b07d
change func name
alexpantyukhin Nov 2, 2022
459133c
Update data_structures/binary_tree/is_bst.py
alexpantyukhin Nov 2, 2022
365cceb
review notes fixes.
alexpantyukhin Nov 3, 2022
bebfcd0
Merge branch 'is_binary_search_tree' of https://github.com/alexpantyu…
alexpantyukhin Nov 3, 2022
99c1a5d
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] Nov 3, 2022
896ae3a
fix flake8
alexpantyukhin Nov 3, 2022
f488438
fix flake 8
alexpantyukhin Nov 3, 2022
4a4d578
fix doctest
alexpantyukhin Nov 3, 2022
60bf506
Update data_structures/binary_tree/is_bst.py
cclauss Nov 3, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions data_structures/binary_tree/is_bst.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""
Author : Alexander Pantyukhin
Date : November 2, 2022

Task:
Given the root of a binary tree, determine if it is a valid binary search
tree (BST).

A valid binary search tree 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.

Implementation notes:
Depth-first search approach.

leetcode: https://leetcode.com/problems/validate-binary-search-tree/

Let n is the number of nodes in tree
Runtime: O(n)
Space: O(1)
"""

from __future__ import annotations

from dataclasses import dataclass


@dataclass
class TreeNode:
data: float
left: TreeNode | None = None
right: TreeNode | None = None


def is_binary_search_tree(root: TreeNode | None) -> bool:
"""
>>> is_binary_search_tree(TreeNode(data=2,
... left=TreeNode(data=1),
... right=TreeNode(data=3))
... )
True

>>> is_binary_search_tree(TreeNode(data=0,
... left=TreeNode(data=-11),
... right=TreeNode(data=3))
... )
True

>>> is_binary_search_tree(TreeNode(data=5,
... left=TreeNode(data=1),
... right=TreeNode(data=4, left=TreeNode(data=3)))
... )
False

>>> is_binary_search_tree(TreeNode(data='a',
... left=TreeNode(data=1),
... right=TreeNode(data=4, left=TreeNode(data=3)))
... )
Traceback (most recent call last):
...
ValueError: Each node should be type of TreeNode and data should be float.

>>> is_binary_search_tree(TreeNode(data=2,
... left=TreeNode([]),
... right=TreeNode(data=4, left=TreeNode(data=3)))
... )
Traceback (most recent call last):
...
ValueError: Each node should be type of TreeNode and data should be float.
"""

# Validation
def is_valid_tree(node: TreeNode | None) -> bool:
"""
>>> is_valid_tree(None)
True
>>> is_valid_tree('abc')
False
>>> is_valid_tree(TreeNode(data='not a float'))
False
>>> is_valid_tree(TreeNode(data=1, left=TreeNode('123')))
False
"""
if node is None:
return True

if not isinstance(node, TreeNode):
return False

try:
float(node.data)
except (TypeError, ValueError):
return False

return is_valid_tree(node.left) and is_valid_tree(node.right)

if not is_valid_tree(root):
raise ValueError(
"Each node should be type of TreeNode and data should be float."
)

def is_binary_search_tree_recursive_check(
node: TreeNode | None, left_bound: float, right_bound: float
) -> bool:
"""
>>> is_binary_search_tree_recursive_check(None)
True
>>> is_binary_search_tree_recursive_check(TreeNode(data=1), 10, 20)
False
"""

if node is None:
return True

return (
left_bound < node.data < right_bound
and is_binary_search_tree_recursive_check(node.left, left_bound, node.data)
and is_binary_search_tree_recursive_check(
node.right, node.data, right_bound
)
)

return is_binary_search_tree_recursive_check(root, -float("inf"), float("inf"))


if __name__ == "__main__":
import doctest

doctest.testmod()