View plaincopy to clipboardprint? # Include "stdafx. h"
# Include <iostream>
# Include <algorithm>
Using namespace std;
Struct Node
{
Int element;
Node * left;
Node * right;
Node (int ele = 0, Node * l = NULL, Node * r = NULL)
: Element (ele), left (l), right (r ){}
};
// Insert a node
Void InsertNode (Node * & root, int element)
{
If (NULL = root)
Root = new Node (element );
Else if (element <root-> element)
InsertNode (root-> left, element );
Else
InsertNode (root-> right, element );
}
// Create a binary search tree
Void CreateBinSearchTree (Node * & root, int arr [], int n)
{
For (int I = 0; I <n; ++ I)
InsertNode (root, arr [I]);
}
// Output in the middle order
Void MiddlePrint (Node * root)
{
If (NULL! = Root)
{
MiddlePrint (root-> left );
Cout <root-> element <"";
MiddlePrint (root-> right );
}
}
// Function: Binary Decision Tree Determination Algorithm
/*
Algorithm idea: Based on the characteristics of a binary tree, "sequential traversal sequence is an ordered sequence", the binary tree is traversed in a central order,
Check the size of the current node and the value of the forward keyword.
*/
// Determines whether the given binary tree is a binary sorting tree during the process of central order traversal. If the binary tree is input, the return value is true. Otherwise, the return value is false.
// Pre points to the forward node of the central order. The initial value is NULL.
Bool IsBinSearchTree (Node * root, Node * pre)
{
If (NULL = root) // The empty binary tree is also a binary sorting tree.
Return true;
// The left subtree is a binary sorting tree with a keyword value greater than the key value of the precursor node,
// At this time, whether it is a binary tree depends on the right subtree
If (IsBinSearchTree (root-> left, pre ))
{
If (NULL = pre) | (pre-> element <root-> element ))
{
Pre = root;
Return IsBinSearchTree (root-> right, pre );
}
}
Else
Return false;
}
Int main ()
{
Const int N = 10;
Int arr [N];
For (int I = 0; I <N; I ++)
Arr [I] = I + 1;
Random_shuffle (arr, arr + N );
Node * root = NULL;
CreateBinSearchTree (root, arr, N );
MiddlePrint (root );
Cout <endl;
Node * pre = NULL;
If (IsBinSearchTree (root, pre ))
Cout <"is a binary sorting tree! "<Endl;
}
Author: "wangyangkobe's column"