Validate Binary Search Tree leetcode Python

Source: Internet
Author: User

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 is binary search trees.

By definition Http://en.wikipedia.org/wiki/Binary_search_tree

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.
The left and right subtree each must also is a binary search tree.
Each node can has up to successor nodes.
There must be no duplicate nodes.
A unique path exists from the root to every and other node.

The left dial hand tree is smaller than the node is less than the right subtree and cannot have duplicate values. The practice is that we compare the values of the left and right nodes each time, and return False if one of the nodes does not meet the criteria

We compare the left and right node key with root key. If any of the condition cannot match the requirement, we return False.

# Definition for a  binary tree node# class treenode:#     def __init__ (self, x): #         self.val = x#         self.left = No ne#         self.right = Noneclass solution:    # @param root, a tree node    # @return A Boolean    def testnode (self,root , minval,maxval):        if Root==none:            return True        if Root.val>maxval or root.val<minval:            return False        return Self.testnode (ROOT.LEFT,MINVAL,ROOT.VAL-1) and Self.testnode (Root.right,root.val+1,maxval)    def isvalidbst (self, root):                minval=-3147483648        maxval=3147483648        return Self.testnode (Root, Minval,maxval)



Validate Binary Search Tree leetcode Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.