Description:Given the root
of a binary tree, determine if it is a valid binary search tree (BST).
A valid BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node's key.
- The right subtree of a node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees must also be binary search trees.
Link: 98. Validate Binary Search Tree
Examples:
Example 1:
Input: root = [2,1,3] Output: true Example 2:
Input: root = [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4.
思路: 做过了上面的那道为二叉搜索树换位置,觉得这个好简单,却是机关重重。首先我们会想,记录前一个节点pre,然后值大于当前就返回False,然后会发现错了,为什么?因为这是在递归里返回False,而没有彻底从函数栈中出来,所以还是要记录遍历的过程有没有过False的情况,如果有,在总函数中返回False. 但是[1,1]这个case没过,所以条件不是大于,是大于等于,然后在过了。
class Solution(object): def isValidBST(self, root): """ :type root: TreeNode :rtype: bool """ self.pre = None self.a = [] self.Inorder(root) if self.a: return False return True def Inorder(self, root): if not root: return self.Inorder(root.left) if self.pre and self.pre.val >= root.val: self.a.append(False) self.pre = root self.Inorder(root.right)
日期: 2021-03-16