假设二叉树bt采用二叉链表存储在二叉树bt中查找值为x的结点试编写算法打印值为x的结点的所有祖先假设值为x的结点不多于一个。请用c语言实现并分析时间复杂度和空间复杂度
算法如下:
void findAncestors(BiTree bt, int x) {
if (bt == NULL) { // 空树直接返回
return;
}
if (bt->data == x) { // 找到目标节点,打印祖先
return;
}
if (bt->lchild != NULL && bt->lchild->data == x || bt->rchild != NULL && bt->rchild->data == x) { // x为当前节点的左/右子节点
printf("%d ", bt->data);
return;
}
findAncestors(bt->lchild, x); // 在左子树中查找
if (bt->lchild != NULL && bt->lchild->data == x) { // x在左子树中
printf("%d ", bt->data); // 打印当前节点
return;
}
findAncestors(bt->rchild, x); // 在右子树中查找
if (bt->rchild != NULL && bt->rchild->data == x) { // x在右子树中
printf("%d ", bt->data); // 打印当前节点
return;
}
}
时间复杂度分析:整个算法在二叉树中最多遍历每个节点一次,因此时间复杂度为O(n),其中n为二叉树中的节点数。
空间复杂度分析:递归调用栈的深度最多为树的高度,因此空间复杂度为O(h),其中h为二叉树的高度
原文地址: https://www.cveoy.top/t/topic/dxz2 著作权归作者所有。请勿转载和采集!