美文网首页
Validate Binary Search Tree in p

Validate Binary Search Tree in p

作者: 你过来啊2018 | 来源:发表于2018-02-24 21:14 被阅读0次

    问题链接

    https://leetcode.com/explore/interview/card/top-interview-questions-easy/94/trees/625/

    解题思路

    • 二叉树中序遍历
    • 注意点:初始变量不能写在递归函数内,不然每次都会被初始化为None

    错误答案

    class Solution(object):
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
            preNode = None
            if root:
    
                if not self.isValidBST(root.left):
                    return False
    
                if preNode and preNode.val >= root.val:
                    return False
    
                preNode = root
    
                if not self.isValidBST(root.right):
                    return False
    
            return True
    

    正确答案

    class Solution(object):
        preNode = None
        def isValidBST(self, root):
            """
            :type root: TreeNode
            :rtype: bool
            """
    
            if root:
    
                if not self.isValidBST(root.left):
                    return False
    
                if self.preNode and self.preNode.val >= root.val:
                    return False
    
                self.preNode = root
    
                if not self.isValidBST(root.right):
                    return False
    
            return True
    

    相关文章

      网友评论

          本文标题:Validate Binary Search Tree in p

          本文链接:https://www.haomeiwen.com/subject/lyjcxftx.html