题目说明: 栈S中保存非负整数,设计一个算法,根据栈S建立二叉排序树。
递归方式
BiSortTreeNode* Insert(BiSortTree &T, DataType data) {
if (T == NULL) {
T = (BiSortTreeNode*)malloc(sizeof(BiSortTreeNode));
T->data = data;
T->lchild = NULL;
T->rchild = NULL;
} else {
if (T->data > data) T->lchild = Insert(T->lchild, data);
else if (T->data <= data) T->rchild = Insert(T->rchild, data);
}
return T;
}
void CreateBiSortTree01(Stack &S, BiSortTree &T) {
while (!IsEmpty(S)) {
int data = 0;
Pop(S, data);
Insert(T, data);
}
}
时间复杂度:栈中元素数量n,每次插入的时间复杂度为O(logn),所以总的时间复杂度为O(nlogn)。
空间复杂度:在插入一个元素时,每次递归的空间复杂度为O(1),递归调用栈的最大深度为logn,所以插入完一个元素的递归空间复杂度为O(1)*logn=O(logn);而每次递归中又需要创建一个新结点,最终需要创建n个新结点,空间复杂度为O(n);所以整个算法的空间复杂度为O(logn)+O(n)=O(n)。
非递归方式
void CreateBiSortTree02(Stack& S, BiSortTree& T) {
while (!IsEmpty(S)) {
BiSortTreeNode* p = T, *q = T;
DataType data = 0;
Pop(S, data);
BiSortTreeNode* node = (BiSortTreeNode*)malloc(sizeof(BiSortTreeNode));
node->data = data;
node->lchild = node->rchild = NULL;
if (T == NULL) T = node;
else {
while (p) {
q = p;
if (T->data > data) p = p->lchild;
else if (T->data < data) p = p->rchild;
}
if (q->data > node->data) q->lchild = node;
else q->rchild = node;
}
}
}
时间复杂度:O(nlogn)
空间复杂度:只需要创建n个新结点,所以为O(n)