原题:https://leetcode.com/problems/validate-binary-search-tree/description/
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a 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.
即是否为二叉查找树。
思路:
一个binary-tree有效,要求root节点的左子树的节点的值都小于root节点的值,root节点的右子树的节点的值都大于root节点的值。所以遍历时只要判断节点的值是否处于该子树的允许范围即可。
代码:
# 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
"""
return self.helper(root, None, None)
def helper(self, root, leftbound, rightbound):
if root is None:
return True
if (leftbound and leftbound.val >= root.val or
rightbound and rightbound.val <= root.val):
return False
return (self.helper(root.left, leftbound, root) and
self.helper(root.right, root, rightbound))