p_string

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

二叉树的前序遍历是:根结点、左结点、右结点

假设我们要构造的二叉树是:前序遍历ABDCE,因程序中要知道叶子结点,扩展后为AB#D##C#E##

代码如下图所示: 

#include <stdio.h>
#include <stdlib.h>
//二叉树的结构
typedef struct tree *BinTree;
struct tree{
    char data;
    BinTree left;
    BinTree right;
};
//前序遍历递归构造二叉树
BinTree BuildBinTree()
{
    char data;
    BinTree root;
    scanf("%c",&data);
    
    if (data == '#'){
        root = NULL; 
    }
    else
    {
        root = (BinTree)malloc(sizeof(struct tree));
        root->data = data;
        root->left = BuildBinTree();
        root->right = BuildBinTree();
    }
    return root;
}
//前序遍历进行验证
void PreTraversalTree(BinTree root)
{
    if (root != NULL)
    {
        printf("%c",root->data);
        PreTraversalTree(root->left);
        PreTraversalTree(root->right);
    }
}
int main()
{
    BinTree root;
    printf("create Binary Tree\n");
    root = BuildBinTree();
    printf("\n");
    PreTraversalTree(root);
    system("pause");
    return 0;

}

输出结果:

 

posted on 2016-08-13 15:44  p_string  阅读(857)  评论(0编辑  收藏  举报