1递归构造二叉排序树
#include "binary_sort_tree.h"
BiTreeNode* insertBiSortTree(BiTreeNode *root, int key){
if (root == NULL) {//递归出口 插入
root = (BiTreeNode*)malloc(sizeof(BiTreeNode));
//BiTreeNode *parent = root;
root->data = key;
root->left = NULL;
root->right = NULL;
}
else if (key < root->data) {
BiTreeNode* parent = root;
parent->left = insertBiSortTree(root->left, key);
root = parent;
}
else if (key > root->data) {
BiTreeNode* parent = root;
parent->right = insertBiSortTree(root->right, key);
root = parent;
}
return root;
}
BiTreeNode* creatBiSortTree(int* arr, int n)
// 功能:实现创建升序二叉排序树
// 输入:无序整数数列arr,数列个数n
// 返回:升序二叉排序树根节点
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
BiTreeNode* BT=NULL;
for (int i = 0; i < n; i++) {
BT = insertBiSortTree(BT, arr[i]);//需要每次都传入根节点 就需要每次返回根结点
}//遍历数组构造树 插入函数有返回值 必须递归
return BT;
/********** End **********/
}
2中序遍历二叉排序树
#include "binary_sort_tree.h"
int* InOrder(BiTreeNode* root, int* arr, int& i)
// 功能:实现升序二叉排序树的中序遍历
// 参数:二叉树根节点root,整数数列arr,起始下标i=0
// 返回:中序遍历数列arr 中序遍历放入数组中
{//非递归中序遍历
BiTreeNode* stack[60];
int stackTop = -1;
BiTreeNode* pMove = root;
while (stackTop != -1 || pMove != NULL) {
while (pMove) {
stack[++stackTop] = pMove;
pMove = pMove->left;//深度 直到左子树遍历完
}//无路可走 出栈
if (stackTop != -1) {
pMove = stack[stackTop--];//取栈顶
arr[i++]=pMove->data;
pMove = pMove->right;
}
}
return arr;
}
bool isOrder(int* arr, int n)
// 功能:判断数列arr是否升序
// 参数:数列arr,数列个数n
// 返回:若升序返回true,否则返回false
{
// 请在这里补充代码,完成本关任务
/********** Begin *********/
for (int i = 0; i + 1 < n; i++) {
if (!(arr[i] < arr[i + 1]))return false;
}return true;
/********** End **********/
}