"Leetcode" Validate Binary Search Tree Problem Solving report

Source: Internet
Author: User

Today CSDN Blog Unusual, tossing the most of the day finally issued this blog post.

Topic

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.
Resolution

Test instructions: Determines whether a binary tree is a two-point search tree.

What is a two-point search tree? 1) The value of the Zuozi is smaller than the root node, 2) The right subtree is larger than the root node, 3) the left and the sub-tree must satisfy the above two conditions.

It is important to note that all nodes of the Zuozi are smaller than the root node, not just the child whose left is smaller than its small, right subtree. It is very easy to make an error that many people tend to only consider each root node smaller than its left child larger than its right child. such as the following non-binary search tree, if only the node and its left and right children's relationship size, it is satisfied.

5
  /     \
4 Ten
      /      \
3

"Error code demonstration" "NA"

/** * Definition for Binary tree * public class TreeNode {*     int val, *     TreeNode left, *     TreeNode right; *
   
    treenode (int x) {val = x;} *} */public class Solution {public    Boolean isvalidbst (TreeNode root) {        if (root = = NULL) return true;        if (root.left! = null && root.val <= root.left.val) return false;        if (root.right! = null && root.val >= root.right.val) return false;        Return Isvalidbst (Root.left) && isvalidbst (root.right);    }}
   


"Violent Traversal Method" "AC"

Recursively starts from the root node, traversing all nodes. At each node, the left and right sub-trees are traversed, and the maximum value of the leftmost subtree is smaller than that of the tree, and the minimum value is larger.

The time complexity is O (n^2).

public class Solution {public    Boolean isvalidbst (TreeNode root) {        if (root = null) return true;        if (!dfsleft (Root.left, root.val) | | |!dfsright (root.right, Root.val)) return false;        Return Isvalidbst (Root.left) && isvalidbst (root.right);    }        public Boolean dfsleft (TreeNode root, int value) {        if (root = null) return true;        if (root.val >= value) return false;        Return Dfsleft (Root.left, value) && dfsleft (root.right, value);    }        public Boolean dfsright (TreeNode root, int value) {        if (root = null) return true;        if (root.val <= value) return false;        Return Dfsright (Root.left, value) && dfsright (root.right, value);}    }


"Failure o (n) Solution: Maximum minimum Value method" "NA"

Integer.min_value and Integer.max_value are employed by the Internet to help solve this problem, that is, the time elapsed record a current maximum and minimum value allowed.

public class Solution {public    Boolean isvalidbst (TreeNode root) {        if (root = null) return true;        if (Root.left = = NULL && Root.right = = null) return true;        return validate (Root, Integer.min_value, integer.max_value);    }        public Boolean validate (TreeNode root, int min, int max) {        if (root = null) return true;        if (root.val <= min | | root.val >= max) return false;        Return Validate (Root.left, Min, root.val) && Validate (Root.right, Root.val, max);}    }

But now the Leetcode has updated the problem, the following solution is not enough, because the Leetcode more than two test cases:

Input: { -2147483648,#,2147483647}
Output: False
Expected: True


"Correct o (n) Solution: Middle Sequence Traversal" "AC" "Recommended"

The middle order traversal result of a binary lookup tree is an ascending sequence.

public class Solution {    list<integer> List = new arraylist<integer> ();        public Boolean isvalidbst (TreeNode root) {        if (root = null) return true;        if (Root.left = = NULL && Root.right = = null) return true;        Inordertraversal (root);        for (int i = 1; i < list.size (); i++) {            if (list.get (i) <= list.get (i-1)) return false;        }        return true;     }        public void Inordertraversal (TreeNode root) {        if (root = null) return;        Inordertraversal (root.left);        List.add (root.val);        Inordertraversal (root.right);    }}

Oddly enough, this method and the above brute-force traversal methods consume 500ms of time on the Leetcode.


"Mid-sequence traversal method Upgrade"

See a more advanced on-line sequential traversal notation, no additional o (n) space is required, and the time passed is 436ms. Come and learn a bit.

public class Solution {    //Keep The previous value in Inorder traversal.    TreeNode pre = null;        public Boolean isvalidbst (TreeNode root) {        //Traverse the tree in Inorder.        if (root = null) {            //inorder traversal:left first.            if (!isvalidbst (Root.left)) return false;                        Compare it with the previous value in Inorder traversal.            if (pre! = null && root.val <= pre.val) return false;                        Update the previous value.            Pre = root;                        Inorder Traversal:right last.            Return Isvalidbst (root.right);        }        return true;     }}

It is important to note that the TreeNode pre = NULL; Be sure to declare outside the method, the original blog is written in the method is not right, because written in the words, each recursion is a different pre.


Reference Source:

http://huntfor.iteye.com/blog/2070278

http://www.geeksforgeeks.org/a-program-to-check-if-a-binary-tree-is-bst-or-not/

"Leetcode" Validate Binary Search Tree Problem Solving report

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.