mycode 不会
注意:root的值要比左子树上所有的数大
参考
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # in valid BST, in-order taversal would go # from node with the smallest value (left most leaf) # up to the node with the biggest value (right most leaf) class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True self.inorder = [] def _dfs(node): if node.left: _dfs(node.left) self.inorder.append(node) if node.right: _dfs(node.right) _dfs(root) prev = self.inorder[0].val for node in self.inorder[1:]: print(node.val) if node.val > prev: prev = node.val else: return False return True
# 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 """ def inorder(root, output): if not root: return if root.left: inorder(root.left, output) output += [root.val] if root.right: inorder(root.right, output) output=[] inorder(root, output) for i in range(1,len(output)): if output[i]<=output[i-1]: return False return True
class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ import sys min_val = -sys.maxsize max_val = sys.maxsize return self.isValidBST_Util(root, min_val, max_val) def isValidBST_Util(self, root, min_val, max_val): if not root: return True if root.val > min_val and root.val < max_val and self.isValidBST_Util(root.left, min_val, root.val) and self.isValidBST_Util(root.right, root.val, max_val): return True else: return False