二叉树的生成和遍历
来源:互联网 发布:哈工大软件下载 编辑:程序博客网 时间:2024/06/09 14:44
#include<iostream>using namespace std;typedef struct node *tree_pointer;struct node{ char ch; tree_pointer left_child,right_child;};tree_pointer root=NULL;tree_pointer create(tree_pointer ptr){ char ch; scanf("%c",&ch); if(ch==' ') ptr=NULL; else{ ptr=(tree_pointer)malloc(sizeof(node)); ptr->ch=ch; ptr->left_child=create(ptr->left_child); ptr->right_child=create(ptr->right_child); } return ptr;} void preorder(tree_pointer ptr){ if(ptr){ printf("%c",ptr->ch); preorder(ptr->left_child); preorder(ptr->right_child); }}void inorder(tree_pointer ptr){ if(ptr){ inorder(ptr->left_child); printf("%c",ptr->ch); inorder(ptr->right_child); }}int leaf(tree_pointer ptr){ if(!ptr) return 0; else{ if(!ptr->left_child&&!ptr->right_child) return 1; return leaf(ptr->left_child)+leaf(ptr->right_child); }}void main(){ printf("构建一个二叉树:\n"); root=create(root); printf("前序遍历二叉树:\n"); preorder(root); printf("\n"); printf("中序遍历二叉树:\n"); inorder(root); printf("\n"); printf("二叉树的叶子结点个数为%d\n",leaf(root)); system("pause");}