根据树的后序判断是不是二叉搜索树。
关键树的后序序列规律是根是最后的,而右子树都大于根,左子树都小于根。可以判断序列是否满足这个条件,然后递归判断左右子树即可。
#include<iostream>
#include<string>
using namespace std;
bool IsSearchBinaryTree(int *numbers,int begin,int end){
if(numbers == NULL || begin>end)
return false;
if(begin == end)
return true;
int root = numbers[end];
int i = end-1;
bool bleft,bright;
//右子树都大于根值
while(i>=begin && numbers[i] > root)
i--;
int j = i;
//左子树都小于根值
while(j>=begin && numbers[j] <root)
j--;
//如果还有结点剩余则不满足搜索二叉树性质
if(j >=begin)
return false;
//判断左右子树是否为搜索二叉树
bleft = bright = true;
if(i >= begin)
bleft = IsSearchBinaryTree(numbers,begin,i);
if(i <end-1)
bright= IsSearchBinaryTree(numbers,i+1,end-1);
return (bleft && bright);
}
int main(){
bool test1,test2;
int number1[] = {5,7,6,9,11,10,8};
test1 = IsSearchBinaryTree(number1,0,6);
if(test1)
printf("number1 is binary search sequence\n");
else
printf("number1 is not binary search sequence\n");
int number2[] = {2,3,5,4,1,2,8};
test2 = IsSearchBinaryTree(number2,0,6);
if(test2)
printf("number2 is binary search sequence\n");
else
printf("number2 is not binaru search sequence\n");
system("PAUSE");
return 0;
}
路径指的是从根到叶子结点。可以用dfs。
#include<iostream>
#include<string>
#include<queue>
using namespace std;
struct Binarytree{
int value;
Binarytree *left;
Binarytree *right;
};
int path[20];
Binarytree* Buildtree(){
int x;
scanf("%d",&x);
if(x == 0)
return NULL;
queue<Binarytree *> Bq;
Binarytree* root = (Binarytree *)malloc(sizeof(Binarytree));
root->value = x;
root->left = NULL;
root->right = NULL;
Binarytree* temp = root;
Bq.push(temp);
while(!Bq.empty()){
temp = Bq.front();
Bq.pop();
if(temp->left == NULL){
int x;
printf("输入%d的左结点\n",temp->value);
scanf("%d",&x);
if(x!=0){
Binarytree * tleft = (Binarytree *)malloc(sizeof(Binarytree));
tleft->value = x;
tleft->left = tleft->right = NULL;
temp->left = tleft;
Bq.push(tleft);
}
}
if(temp->right == NULL){
int x;
printf("输入%d的右结点\n",temp->value);
scanf("%d",&x);
if(x!=0){
Binarytree * tright = (Binarytree *)malloc(sizeof(Binarytree));
tright->value = x;
tright->left = tright->right = NULL;
temp->right = tright;
Bq.push(tright);
}
}
}
return root;
}
//sum表示要求的路径值,current和path用来记录路径
void printtree(int sum,int current,int path[],Binarytree* root){
if(sum <0)
return;
path[current] = root->value;
++current;
sum -= root->value;
if(sum == 0 && root->left==NULL && root->right == NULL){
printf("find a path:\n");
for(int i =0;i<current;i++)
printf("%d ",path[i]);
printf("\n");
return;
}
if(root->left)
printtree(sum,current,path,root->left);
if(root->right)
printtree(sum,current,path,root->right);
}
int main(){
Binarytree *root = Buildtree();
printtree(22,0,path,root);
system("PAUSE");
return 0;
}