1. 程式人生 > >C語言建立一個二叉樹

C語言建立一個二叉樹

如何建立一個二叉樹,先序遍歷,中序遍歷。

#include <stdio.h>
#include <stdlib.h>

#include<bits/stdc++.h>
#define NULLKEY '?'

typedef struct btnode
{
    char data;
    struct btnode *lchild,*rchild;
}btnode,*bitree;
//建立一個二叉樹

bitree preCreateBitree(bitree &root)
{
    char ch;
    scanf("%c",&ch);
    if
(ch==NULLKEY) { root=NULL; return(root); } else { root=(bitree)malloc(sizeof(btnode)); root->data=ch; preCreateBitree(root->lchild); preCreateBitree(root->rchild); return(root); } } void fsearch(bitree root) { if
(root==NULL) return ; else { printf("%c",root->data); //先序遍歷每個結點的值 fsearch(root->lchild); fsearch(root->rchild); } } void msearch(bitree root) { if(root==NULL) return ; else { msearch(root->lchild); printf("%c"
,root->data); //中序遍歷每個結點的值 msearch(root->rchild); } } int main() { bitree root; root = preCreateBitree(root); printf("first:"); fsearch(root); printf("\n"); printf("middle:"); msearch(root); printf("\n"); }