given a list, check if it’s valid BST(left<node.val<right)
2. init
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right classSolution: defisValidBST(self, root: Optional[TreeNode]) -> bool:
3. thought
221220: recursive - no, need argument to valid, root val with left/right val, and return true/false.
221221: recursive ok!
inOrder walk from smallest to biggest.
val bigger list[-1], and add it into list
val less list[-1], reutrn False
return Left AND Right result.
4. trouble
still need global variable.
5.final solution
classSolution: # 1. inOrder walk from smallest to biggest. # 2. val bigger list[-1], and add it into list # 3. val less list[-1], reutrn False # 4. return Left AND Right result. _list = [] defisValidBST(self, root: Optional[TreeNode]) -> bool: self._list = [] return self.inOrder(root) definOrder(self, root: Optional[TreeNode]) -> bool: if root isNone: returnFalse _L, _R = True, True if root.left: _L = self.inOrder(root.left)