1. 程式人生 > >LeetCode 98 Validate Binary Search Tree(Python詳解及實現)

LeetCode 98 Validate Binary Search Tree(Python詳解及實現)

【題目】

Given a binary tree, determine if it is avalid binary search tree (BST).

Assume a BST is defined as follows:

The left subtree of a node contains onlynodes with keys less than the node's key.

The right subtree of a node contains onlynodes with keys greater than the node's key.

Both the left and right subtrees must alsobe binary search trees.

Example 1:

    2

   /\

 1   3

Binary tree [2,1,3], return true.

Example 2:

    1

   /\

 2   3

Binary tree [1,2,3], return false.

給定一個二叉樹,判斷是不是合法的二叉搜尋樹。

【思路】

一:遞迴。(當前節點值比他左子樹大,比右子樹小)

1. 為空返回true

2.左子樹返回的合法性。考慮左子樹不空的時候,那麼根結點要比所有左子樹上的結點大,即根結點大於左子樹的最大值----左子樹的右下角的結點。

3. 左子樹返回為真且右子樹也為真則返回真。考慮右子樹時,根要比右子樹的最小值小---最左左下角的結點。

【Python實現】

# -*-coding: utf-8 -*-
"""
Createdon Fri Aug 11 10:51:35 2017
 
@author:Administrator
"""
 
#Definition for a binary tree node.
classTreeNode(object):
     def __init__(self, x):
         self.val = x
         self.left = None
         self.right = None
 
classSolution(object):
    def isValidBST(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        return self.valid(root, None, None)
               
    def valid(self, root, min, max):
        if root == None or root.val == None:
            return True
       
        if (min is not None and root.val <=min) or (max is not None and root.val >= max):
            print(1)
            return False
       
        return self.valid(root.left, min,root.val) and self.valid(root.right, root.val, max)
   
   
       
if__name__ == '__main__':
    S = Solution()
    l1 = TreeNode(9)
    l2 = TreeNode(5)
    l3 = TreeNode(11)
    l4 = TreeNode(2)
    l5 = TreeNode(7)
    l6 = TreeNode(10)
    l7 = TreeNode(14)
    l8 = TreeNode(1)
    l9 = TreeNode(3)
    l10 = TreeNode(6)
    l11 = TreeNode(8)
    l12 = TreeNode(12)
    l13 = TreeNode(15)
   
    root = l1
   
    l1.left = l2
    l1.right = l3
   
    l2.left = l4
    l2.right = l5
    l3.left = l6
    l3.right = l7
   
    l4.left = l8
    l4.right = l9
    l5.left = l10
    l5.right = l11
    l7.left = l12
    l7.right = l13
   
    S.isValidBST(root)