问题链接
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