定义二叉树结点,创建二叉树,分别利用先序非递归算法、输出结果。

定义二叉树结点,创建二叉树,分别利用先序非递归算法、输出结果。,第1张

定义二叉树结点,创建二叉树,分别利用先序非递归算法、输出结果。

定义二叉树结点,创建二叉树,分别利用先序非递归算法、输出结果。

头文件:
#include
#include
typedef struct node{
char data;
struct node *left;
struct node *right;
}Node, *Tree;
Tree create_tree(){
Node root = NULL;
char ch;
scanf("%c", &ch);
if (ch != ‘#’){
root = (Node
)malloc(sizeof(Node));
root->data = ch;
root->left = create_tree(); // 递归创建
root->right = create_tree();
}
else{root = NULL;}
return root;
}
// 非-递归前序遍历二叉树
void preOrderNRec(Tree root)
{
Tree stack[20], node;//定义一个 树节点数组进行栈 *** 作
int top = 0;
if (root == NULL)
{printf(“树为空n”);return;}
else
{
top++;
stack[top] = root; // 将根节点入栈
while (top > 0)
{ node = stack[top–];
printf(" %c", node->data);
if (node->right != NULL)
{stack[++top] = node->right; } // 入栈
if (node->left != NULL)
{stack[++top] = node->left;}
}
}
}

主函数:
int main()
{
printf(“请输入先序排列的二叉树,空节点为# n”);
Tree root = create_tree();
printf(“非递归实现前序遍历— n”);
preOrderNRec(root);
printf("n");
return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/zaji/5670034.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存