Topic source: 98. Verification of binary search tree
title:
Give you the root node root of a binary tree, and determine whether it is a valid binary search tree.
An efficient binary search tree is defined as follows:
- The left subtree of a node contains only numbers less than the current node.
- The right subtree of a node contains only numbers greater than the current node.
- All left and right subtrees must themselves be binary search trees.
Idea: In-order traversal
sees that the left node is smaller than the root node, and the right node is larger than the root node. I immediately thought that it might be related to in-order traversal. I looked at the answer and it was true. The idea is out, oh yeah
, the conditions given by the title are very similar to the rules of in-order traversal, so as long as the array obtained after in-order traversal is strictly in ascending order, that is, five repetitions, so at the end, a set function length judgment. The specific code is as follows:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
res = []
def InOrderTraverse(r):
if not r:
return
InOrderTraverse(r.left)
res.append(r.val)
InOrderTraverse(r.right)
InOrderTraverse(root)
if res == sorted(res) and len(res) == len(set(res)):
return True
else:
return False
I don’t know if there is a better solution in the final judgment. I feel that the final running time and space are not very good. Partners with good ideas can discuss it together~
Reference link: Python Verification Binary Search Tree
LeetCode-Python- 98. Verify Binary Search Tree