二叉树 二叉树带虚结点表示的先序遍历可以确定唯一一颗二叉树

二叉树模版变形

#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<queue>
using namespace std;
typedef struct BiTNode{
    char data;
    struct BiTNode *lchild,*rchild;
}BiTNode,*BiTree;
int z=0;                                //***
int CreateBiTree(BiTree &T,char *m)
{
    char data;
    data=*(m+z);
    z++;                            //***
    if(data=='#')
        T=NULL;
    else
    {
        T=(BiTree)malloc(sizeof(BiTNode));
        T->data=data;
        CreateBiTree(T->lchild,m); //*
        CreateBiTree(T->rchild,m);
    }
    return 0;
}
void Visit(BiTree T)
{
    if(T->data!='#')
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是C语言实现二叉树的递归遍算法的代码: ```c #include <stdio.h> #include <stdlib.h> typedef struct TreeNode { char data; struct TreeNode *left; struct TreeNode *right; } TreeNode; //创建二叉树 TreeNode *createTree(char *str, int *index) { if (str[*index] == '#' || str[*index] == '\0') { return NULL; } TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode)); root->data = str[*index]; (*index)++; root->left = createTree(str, index); (*index)++; root->right = createTree(str, index); return root; } // void preOrder(TreeNode *root) { if (root == NULL) { return; } printf("%c ", root->data); preOrder(root->left); preOrder(root->right); } //中 void inOrder(TreeNode *root) { if (root == NULL) { return; } inOrder(root->left); printf("%c ", root->data); inOrder(root->right); } //后 void postOrder(TreeNode *root) { if (root == NULL) { return; } postOrder(root->left); postOrder(root->right); printf("%c ", root->data); } //输出叶子点 void printLeaves(TreeNode *root) { if (root == NULL) { return; } if (root->left == NULL && root->right == NULL) { printf("%c ", root->data); } printLeaves(root->left); printLeaves(root->right); } //统计点个数 int countNodes(TreeNode *root) { if (root == NULL) { return 0; } return countNodes(root->left) + countNodes(root->right) + 1; } int main() { char str[] = "ABD##E##CF#H##G##"; int index = 0; TreeNode *root = createTree(str, &index); printf(":"); preOrder(root); printf("\n"); printf("中:"); inOrder(root); printf("\n"); printf("后:"); postOrder(root); printf("\n"); printf("叶子点:"); printLeaves(root); printf("\n"); printf("点个数:%d\n", countNodes(root)); return 0; } ``` 程的输出果如下: ``` :A B D E C F H G 中:D B E A F C H G 后:D E B H G F C A 叶子点:D E H G 点个数:7 ``` 其中,二叉树的扩展列为"ABD##E##CF#H##G##",其中"#"表示点。在程中,我们首根据扩展列创建了二叉树,然后分别进行了、中、后,并输出了叶子点和点个数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值