lintcode_95.验证二叉树
给定一个二叉树,判断它是否是合法的二叉查找树(BST)
一棵BST定义为:
- 节点的左子树中的值要严格小于该节点的值。
- 节点的右子树中的值要严格大于该节点的值。
- 左右子树也必须是二叉查找树。
- 一个节点的树也是二叉查找树。
样例
一个例子:
2 / \ 1 4 / \ 3 5
思路:左 < root <右 ,依据中序遍历
九章参考:
class Solution: """ @param: root: The root of binary tree. @return: True if the binary tree is BST, or false """ def isValidBST(self, root): # write your code here self.isBST = True self.lastVal = None self.validate(root) return self.isBST def validate(self,root): if root is None: return self.validate(root.left) if self.lastVal is not None and self.lastVal >= root.val: self.isBST = False return self.lastVal = root.val self.validate(root.right)