-->
当前位置:首页 > 题库 > 正文内容

函数题:中序遍历的非递归算法

Luz3年前 (2022-09-15)题库853
要求使用中序遍历的非递归算法实现:打印输出二叉排序树中关键字的值大于X且最靠近X的值。

### 函数接口定义:
c++
void print_x( BinTree BT,int X )

其中 BinTree 的结构定义为:
c++
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};

堆栈的结构定义为:
c++
/*定义堆栈*/
typedef struct SNode *PtrToSNode;
struct SNode{
int top;
BinTree Data[MAXSIZE];
};
typedef PtrToSNode Stack;


### 裁判测试程序样例:
c++
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 100

typedef struct TNode * BinTree; /* 二叉树类型 */
typedef int ElementType;
struct TNode{ /* 树结点定义 */
ElementType Data; /* 结点数据 */
BinTree Left; /* 指向左子树 */
BinTree Right; /* 指向右子树 */
};

/*定义堆栈*/
typedef struct SNode *PtrToSNode;
struct SNode{
int top;
BinTree Data[MAXSIZE];
};
typedef PtrToSNode Stack;

/*初始化堆栈*/
Stack CreateStack()
{
Stack S = (Stack)malloc(sizeof(struct SNode));
S->top = -1;
return S;
}

void print_x( BinTree BT,int X ); /*使用中序遍历的非递归算法实现:打印输出二叉排序树中关键字的值大于X且最靠近X的值 */

//按先序次序输入二叉树中结点的值,0表示空树,构造二叉链表表示二叉树T
BinTree CreatBinTree()
{
ElementType ch;
BinTree T;
scanf("%d",&ch); /*按先序次序输入树的结点,空树输入0*/
if(ch == 0)
T = NULL;
else {
T = (BinTree)malloc(sizeof(struct TNode));
T->Data = ch;
T->Left = CreatBinTree();
T->Right = CreatBinTree();
}
return T;
}

int main()
{
int x;
BinTree BT;
BT = CreatBinTree();

if(BT == NULL){
printf("\n空树!\n");
}else{
scanf("%d",&x);
print_x( BT,x);
}
return 0;
}

/* 请在这里填写答案 */

![1(1).jpg](~/663ea20e-ba22-4942-b336-82dad74f3522.jpg)

### 输入样例:
in
30 15 0 0 41 33 0 35 34 0 0 0 50 0 0
35


### 输出样例:
out
二叉排序树中关键字的值大于35且最靠近35的值为:41







答案:若无答案欢迎评论

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。