else
if (ptr->data > key1){
path1[pathLen1] = ptr->data;
pathLen1 ++;
ptr = ptr->lchild;
}
else
if (ptr->data < key1){
path1[pathLen1] = ptr->data;
pathLen1 ++;
ptr = ptr->rchild;
}
}
ptr = root;
int path2[1000];
int pathLen2 = 0;
while (ptr != NULL){
if (key2 == ptr->data){
path2[pathLen2] = ptr->data;
pathLen2 ++;
printArray(path2,pathLen2);
break;
}
else
if (ptr->data > key2){
path2[pathLen2] = ptr->data;
pathLen2 ++;
ptr = ptr->lchild;
}
else
if (ptr->data < key2){
path2[pathLen2] = ptr->data;
pathLen2 ++;
ptr = ptr->rchild;
}
}
int i = pathLen1 - 1;
//key1和key2有序,
if (key2 < key1){
key2 = key2^key1;
key1 = key2^key1;
key2 = key2^key1;
}
for (; i > 0; i --){
if (key1 < path1[i] && path1[i]< key2){
int result = path1[i];
return result;
}
}
}
//问题6:在二叉树中找出和为某一值的所有路径
void FindPath(treeNode* root, int path[],int pathLen,int expectedSum, int
currentSum){
if (root == NULL)
return;
currentSum += root->data;
path[pathLen] = root->data;
pathLen ++;
if (currentSum == expectedSum && root->lchild == NULL && root->rchild ==
NULL){
printArray(path,pathLen);
}
if (root->lchild != NULL){
FindPath(root->lchild,path,pathLen,expectedSum,currentSum);
}
if (root->rchild != NULL){
FindPath(root-
>rchild,path,pathLen,expectedSum,currentSum);
}
currentSum -= root->data;
}
//问题7:怎样编写一个程序,把一个有序整数数组放到二叉树中?
void createTreeFromArray(int a[], int begin, int end, treeNode** root){
if (begin > end)
return;
else{
*root = (treeNode*) malloc(sizeof(treeNode));
int mid = (begin + end) / 2;
(*root)->data = a[mid];
(*root)->rchild = NULL;
(*root)->lchild = NULL;
createTreeFromArray(a, begin ,mid - 1, &(*root)->lchild);
createTreeFromArray(a, mid + 1 ,end, &(*root)->rchild);
}
}
//问题8:判断整数序列是不是二叉搜索树的后//序遍历结果
int isPostTraverse(int a[], int begin ,int end){
if(begin >= end)
return 1;
else{
int root = a[end];
int lroot;
int i;
int location = begin;
for (i = begin; i < end ; i ++){
if(a[i] > root){
location = i;
lroot = a[i];
break;
}
}
for (i = location + 1; i < end; i++){
if (a[i] < lroot){
return 0;
}
}
int flag1 = isPostTraverse(a,begin,location -1);
int flag2 = isPostTraverse(a,location,end - 1);
if (flag1 && flag2)
return 1;
else
return 0;
}
}
//问题9:求二叉树的镜像
void changeMirror(treeNode** root){
if ( *root == NULL)
return;
else{
treeNode* temp = (*root)->lchild;
(*root)->lchild = (*root)->rchild;
(*root)->rchild = temp;
changeMirror(&(*root)->lchild);
changeMirror(&(*root)->rchild);
}
}