当前位置:   article > 正文

LeetCode-Python-98. 验证二叉搜索树_0098-验证二叉搜索树 leetcode python

0098-验证二叉搜索树 leetcode python

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

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

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

示例 1:

  1. 输入:
  2. 2
  3. / \
  4. 1 3
  5. 输出: true

示例 2:

  1. 输入:
  2. 5
  3. / \
  4. 1 4
  5.   / \
  6.   3 6
  7. 输出: false
  8. 解释: 输入为: [5,1,4,null,null,3,6]。
  9.   根节点的值为 5 ,但是其右子节点值为 4 。

 

思路:

二叉搜索树的条件就是root.left<root<root.right,不就是要求中序遍历严格升序吗?

  1. # Definition for a binary tree node.
  2. # class TreeNode(object):
  3. # def __init__(self, x):
  4. # self.val = x
  5. # self.left = None
  6. # self.right = None
  7. class Solution(object):
  8. def isValidBST(self, root):
  9. """
  10. :type root: TreeNode
  11. :rtype: bool
  12. """
  13. inorder = list()
  14. self.inorderTra(root, inorder)
  15. # print inorder
  16. for i in range(len(inorder)-1):
  17. if inorder[i] >= inorder[i+1]:
  18. return False
  19. return True
  20. def inorderTra(self, root, inorder):
  21. if not root:
  22. return None
  23. self.inorderTra(root.left, inorder)
  24. inorder.append(root.val)
  25. self.inorderTra(root.right, inorder)
  26. return

下面的写于2019.6.24 

  1. class Solution(object):
  2. def isValidBST(self, root):
  3. """
  4. :type root: TreeNode
  5. :rtype: bool
  6. """
  7. def inOrder(node):
  8. if not node:
  9. return []
  10. return inOrder(node.left) + [node.val] + inOrder(node.right)
  11. inorder = inOrder(root)
  12. return len(inorder) == len(set(inorder)) and inorder == sorted(inorder)

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/223034
推荐阅读
相关标签
  

闽ICP备14008679号