Validate Binary Search Tree @ LeetCode

Source: Internet
Author: User
Tags tree serialization

The first thought of recursion, but did not expect to use the upper and lower limit method, but added a parent as the parameter, the result is very troublesome. The code is concise and clear after the upper and lower limits are used.

Package Level3; import Utility. treeNode;/*** Validate Binary Search Tree ** 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. confused what "{1, #, 2, 3}" means?> Read more on how binary tree is serialized on OJ. OJ's Binary Tree Serialization: The serialization of a binary tree follows a level order traversal, where '# 'signiies a path terminator where no node exists below. here's an example: 1/\ 2 3/4 \ 5 The above binary tree is serialized as "{, 3, #,#, 4, #,#, 5 }". **/public class S98 {public static void main (String [] args) {TreeNode root = new TreeNode (3); TreeNode p1 = new TreeNode (1 ); treeNode p2 = new TreeNode (5); TreeNode p3 = new TreeNode (0); TreeNode p4 = new TreeNode (2); TreeNode p5 = new TreeNode (4 ); treeNode p6 = new TreeNode (6); root. left = p1; root. right = p2; p1.left = p3; p1.right = p4; p2.left = p5; p2.right = p6; System. out. println (isValidBST (root);} public static boolean isValidBST (TreeNode root) {return rec (root, Integer. MIN_VALUE, Integer. MAX_VALUE);} // use the minimum and maximum values to specify the subtree range public static boolean rec (TreeNode root, int min, int max) {if (root = null) {return true;} // if (root. val <= min | root. val> = max) {return false;} // check the legality of the left and right subtree and update the upper and lower limits of return rec (root. left, min, root. val) & rec (root. right, root. val, max );}}

 


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.