LeetCode Validate Binary Search Tree

Source: Internet
Author: User

LeetCode Validate Binary Search Tree
LeetCode-based Validate Binary Search Tree

Original question

Determine whether a binary search tree is valid. Effective means that each node has a value greater than or equal to the left node (if there is a corresponding node), and its left and right nodes also meet this condition.

Note:

None

Example:

Input:

  2 / \1   3

Output: True

Solutions

The Binary Tree Inorder Traversal is modified. In the middle-order traversal of the tree, the node sequence is left node, root node, and right node. This means that when a binary search tree meets the requirements, its ordinal traversal sequence must increase progressively. If the preceding node is larger than the following node in the middle-order traversal, it indicates that it does not meet the requirements.

AC Source Code
# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution(object):    def isValidBST(self, root):        """        :type root: TreeNode        :rtype: bool        """        stack = []        curr = root        prev = None        while curr or stack:            while curr:                stack.append(curr)                curr = curr.left            if stack:                curr = stack.pop()                if prev and curr.val <= prev.val:                    return False                prev = curr                curr = curr.right        return Trueif __name__ == "__main__":    None

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.