Binary search tree (5)-Determine if a binary tree is BST

Source: Internet
Author: User

In the first article in this series, we've covered some of the properties of the two-fork lookup tree:
    • Any node value in the left subtree of the node is less than the root node
    • Any node value in the right subtree of the node is greater than the root node
    • The left and right subtree must be a two-fork lookup tree, and no duplicate nodes are allowed.

Based on these properties, it is natural to have this way of judging: Each node in the tree has a specific value.

Suppose the node of the tree is defined as:
struct Node { int key; Node *left; Node *right;};

Method 1 (Implementation is simple, but wrong) for each node, it detects whether its left child node is less than it, and whether the right child node is larger than it.
BOOL Isbst (node* node) {  if (node = = NULL)    return true;       If the left child is larger than the root node, then the BST  if (node->left! = NULL && node->left->key> node->key)    return False ;       If right child node is small root node, then not BST  if (node->right! = NULL && Node->right->key < Node->key)    return false;     Recursive judgment  if (!isbst (node->left) | |!isbst (node->right))    return false;       The test is complete, all conditions pass, then BST  return true;}
However, this method of judging is wrong, as shown in the following example, Node 4 is in the left subtree of root node 3, but the function detects that the tree is BST.
3
/   \
2 5
/  \
1 4

Method 2 (The result is correct, but the efficiency is relatively low) for each node, it detects whether the maximum value in the left subtree is smaller than it, and the right subtree has a greater minimum value.
If it is BST, return Truebool ISBST (node * node) {        if (node = = NULL) return               true;        If the left dial hand tree has a maximum value greater than the root node, it returns false        if (node->left! = NULL && maxValue (node->left) > Node->key)               return false;        Returns False if the right subtree minimum is less than the root node        (node->right! = NULL && minValue (node->right) < Node->key)               return false;        Recursive judgment        if (!isbst (node->left) | |!isbst (node->right))               return (false);        All tests are passed, which is BST        return true;}
where the MaxValue and MinValue functions return the maximum and minimum values in a non-empty tree, respectively.

Method 3 (correct and valid) Method 2 is less efficient because it iterates through some of the data in the tree. The better scenario is that each node is traversed only once. The trick of Method 3 is to limit the range of node values in the subtree so that each node is accessed only once. The initial range of node values can be limited to int_min and Int_max.
Determine if the BST
BOOL Isbst (node* Node)
{
Return (Isbstutil (node, int_min, Int_max));
}
Returns true if it is a binary lookup tree with a value range of [Min,max]
BOOL Isbstutil (node* Node, int min, int max)

Code implementation:
#include <iostream>struct node{int key;        Node *left; Node *right;}; BOOL Isbstutil (node * node, int min, int max);//Determine if Bstbool isbst (node * node) {return (Isbstutil (node, int_min, Int_max));}  If it is a binary lookup tree with a value range of [min, Max], then return Truebool isbstutil (node * node, int min, int max) {//Empty tree is also BST if (node = =        NULL) return true;        If the node value violates the maximum/minimum constraint, it is not the BST if (Node->key < min | | node->key > MAX) return false; Recursive check subtree return isbstutil (node->left, Min, node->key-1) && Isbstutil (Node->righ T, Node->key + 1, max);}       Create a new BST node *createnewnode (int item) {Node *temp = new node;       Temp->key = Item;        Temp->left = Temp->right = NULL; return temp;} int main () {/* tree1 definition 4/2 5/1 3 */Node *root = Crea       Tenewnode (4); Root->left = Createnewnode (2);       Root->right = Createnewnode (5);       Root->left->left = Createnewnode (1);        Root->left->right = Createnewnode (3);        if (Isbst (root)) Std::cout << "Tree1 is bst\n";        else Std::cout << "Tree1 is not bst\n"; /* TREE2 definition 4/2 5//1 3 * * root = Createnewnode (4)       ;       Root->left = Createnewnode (2);       Root->left->left = Createnewnode (1);       Root->right = Createnewnode (5);        Root->right->left = Createnewnode (3);        if (Isbst (root)) Std::cout << "Tree2 is bst\n";        else Std::cout << "Tree2 is not bst\n"; return 0;}
Output:
Tree1 is BST
Tree2 is not BST

Time complexity: O (N)
Secondary space: O (1) If the size of the function call stack is not considered, otherwise O (n)

Method 4 (using the middle order traversal) 1) The tree is traversed in a sequence, and the result is saved in the temp array.
3) detects if the elements in the temp array are in ascending order. If it is, then this tree is BST.
Time complexity: O (N)
Method 4 can also be further optimized, and we can avoid using this extra array. In the middle sequence traversal, the precursor node can be saved, if the current node is less than the predecessor node, then this tree is not BST.
Determine if Bstbool isbst (node* root) {     static Node *prev = NULL;     The middle sequence traverses this tree and saves the precursor node to prev     if (root)     {if (          !isbst (root->left))               return false;          Detects the legitimacy of the node value          if (prev! = NULL && root->key <= prev->key)               return false;          prev = root;          Right subtree          return Isbst (root->right);     }     return true;}

For more information:
Http://en.wikipedia.org/wiki/Binary_search_tree
Http://cslibrary.stanford.edu/110/BinaryTrees.html

Binary search tree (5)-Determine if a binary tree is BST

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.