python --- LeetCode之 98. Validate Binary Search Tree

题目:
Given a binary tree, determine if it is a valid binary search tree (BST).

Assume a BST is defined as follows:

  1. The left subtree of a node contains only nodes with keys less than the node’s key.
  2. The right subtree of a node contains only nodes with keys greater than the node’s key.
  3. Both the left and right subtrees must also be binary search trees.

方法一:
利用中序遍历,如果是二叉搜索树,则中序遍历到的会是递增序列,所以在遍历过程中进行判断,如果当前遍历到的节点值大于前一个遍历到的节点值,则继续,否则返回不是二叉搜索树。
代码如下:

# 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 isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        self.prev = None
        return self.heaper(root)
    def heaper(self,root):
        if root is None:
            return True   
        if self.heaper(root.left) is not True:  # 如果左子树不满足就直接返回
            return False
        if self.prev and self.prev.val >= root.val: # 判断是否节点递增
            return False
        self.prev = root                # 保留前一个遍历到的节点值
        return self.heaper(root.right)  # 判断右子树是否满足

注意:空树也是二叉搜索树
方法二:
递归,用左子树最大值和右子树最小值和根结点比较,如果左子树最大值小于根结点且右子树最小值大于根结点,则是二叉搜索树否则不是。

# 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 isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.valid(root, None, None)   
     def valid(self, node, lower, upper):
        if not node:
            return True
        if lower is not None and lower >= node.val:
            return False
        if upper is not None and upper <= node.val:
            return False
        return self.valid(node.left, lower, node.val) and self.valid(node.right, node.val, upper)  # 左子树和右子树同时满足条件才是二叉搜索树

注意:空树也是二叉搜索树,设置一个最小值,一个最大值,对于左子树最大值就是根结点,对于右子树最小值就是根结点。

你可能感兴趣的:(LeetCode,二叉搜索树)