leetcode--98--验证二叉搜索树

2020-11-11  本文已影响0人  minningl

题目:
给定一个二叉树,判断其是否是一个有效的二叉搜索树。

假设一个二叉搜索树具有如下特征:

节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:

输入:
    2
   / \
  1   3
输出: true

示例 2:

输入:
    5
   / \
  1   4
     / \
    3   6
输出: false

解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。

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

思路:
1、将二叉树按照中序遍历,判断中序遍历的结果是否是递增的

Python代码:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):

    def __init__(self):
        self.inList = []

    def inSort(self, root):
        if not root:
            return None
        self.inSort(root.left)
        self.inList.append(root.val)
        self.inSort(root.right)

    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        self.inSort(root)
        for index,item in enumerate(self.inList):
            if index+1<len(self.inList) and item>=self.inList[index+1]:
                return False
        return True
上一篇 下一篇

猜你喜欢

热点阅读