tree 先序遍历 叶子结点_编程:按先序序列输出二叉树的叶子结点

源程序:

#include

#include

using namespace std;

typedef struct bitreenode

{

char data;

struct bitreenode *lchild, *rchild;

}*Bitree;

//创建二叉树

void createbitree(Bitree &T)

{

char data;

data = getchar();

if (data == '#')

{

T = NULL;

}

else

{

T = new bitreenode;

T->data = data;

createbitree(T->lchild);

createbitree(T->rchild);

}

};

//按先序次序打印叶子结点

void pre_leaf(Bitree T)//T 为根结点指针

{

if (T!= NULL)

{

if (T->lchild == NULL && T->rchild == NULL)

printf("%c", T->data);

pre_leaf(T->lchild);

pre_leaf(T->rchild);

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
非常感谢您的提问。以下是C语言实现二叉树递归遍历的程序,并按要求输出结果。 ``` #include <stdio.h> #include <stdlib.h> // 定义二叉树结构体 typedef struct TreeNode { char data; struct TreeNode *left; struct TreeNode *right; } TreeNode; // 创建二叉树(根据扩展先序遍历序列TreeNode *createTree() { char c; scanf("%c", &c); if(c == '#') { return NULL; } TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode)); root->data = c; root->left = createTree(); root->right = createTree(); return root; } // 先序遍历 void preOrder(TreeNode *root) { if(root == NULL) { return; } printf("%c ", root->data); preOrder(root->left); preOrder(root->right); } // 后序遍历 void postOrder(TreeNode *root) { if(root == NULL) { return; } postOrder(root->left); postOrder(root->right); printf("%c ", root->data); } // 中序遍历 void inOrder(TreeNode *root) { if(root == NULL) { return; } inOrder(root->left); printf("%c ", root->data); inOrder(root->right); } // 输出叶子结点 void leafNodes(TreeNode *root) { if(root == NULL) { return; } if(root->left == NULL && root->right == NULL) { printf("%c ", root->data); } leafNodes(root->left); leafNodes(root->right); } // 统计结点个数 int countNodes(TreeNode *root) { if(root == NULL) { return 0; } return countNodes(root->left) + countNodes(root->right) + 1; } int main() { printf("请输入二叉树的扩展先序遍历序列(#表示结点):\n"); TreeNode *root = createTree(); printf("先序遍历结果:"); preOrder(root); printf("\n后序遍历结果:"); postOrder(root); printf("\n中序遍历结果:"); inOrder(root); printf("\n叶子结点为:"); leafNodes(root); printf("\n结点个数为:%d\n", countNodes(root)); return 0; } ``` 您可以将上面的代码保存为一个名为 `binary_tree.c` 的文件中,并使用 `gcc` 编译器编译运行: ``` gcc binary_tree.c -o binary_tree ./binary_tree ``` 输入扩展先序遍历序列后,程序会按要求输出先序遍历、后序遍历、中序遍历、叶子结点结点个数的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值