Skip to content

98 validate binary search tree#28

Open
kitano-kazuki wants to merge 5 commits intomainfrom
98-validate-binary-search-tree
Open

98 validate binary search tree#28
kitano-kazuki wants to merge 5 commits intomainfrom
98-validate-binary-search-tree

Conversation

@kitano-kazuki
Copy link
Copy Markdown
Owner

Comment on lines +49 to +53
def is_valid_bst_helper(node: TreeNode, minimum_val: int, maximum_val: int) -> bool:
if not (minimum_val < node.val < maximum_val):
return False

is_left_subtree_valid = True
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

フラグを使わないほうがシンプルだと思います。

if node.left is not None:
    if not is_valid_bst_helper(node.left, minimum_val, node.val):
        return False

if node.right is not None:
    if not is_valid_bst_helper(node.right, node.val, maximum_val):
        return False

return True

また、関数の先頭で None をチェックすることで、もう少しシンプルにできそうです。

def isValidBST(self, root: Optional[TreeNode]) -> bool:
    def is_valid_bst_helper(node: TreeNode, minimum_val: int, maximum_val: int) -> bool:
        if node is None:
            return True

        if not (minimum_val < node.val < maximum_val):
            return False

        if not is_valid_bst_helper(node.left, minimum_val, node.val):
            return False

        if not is_valid_bst_helper(node.right, node.val, maximum_val):
            return False

        return True

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

Comment on lines +202 to +204
next_frontier.append((node.right, node.val, maximum_val))
frontier = next_frontier
return True
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(あまりコメントできるところないのですが、強いてコメントすれば)
for 文とwhile文を抜けるところに空行を入れると可読性は上がるかもしれません
https://peps.python.org/pep-0008/#blank-lines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants