zoukankan      html  css  js  c++  java
  • 用前序遍历递归构造二叉树

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

    假设我们要构造的二叉树是:前序遍历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
    ");
        root = BuildBinTree();
        printf("
    ");
        PreTraversalTree(root);
        system("pause");
        return 0;
    
    }

    输出结果:

    只为训练自己,时刻锤炼一个程序员最基本的技能!
  • 相关阅读:
    2017年9月22日 关于JS数组
    2017年9月20日
    2017年9月19日 JavaScript语法操作
    2017年9月18日
    2017年9月17日 JavaScript简介
    2017年9月16日
    2017年9月15日
    2017年9月14日
    2017年9月12日
    贪吃蛇全文
  • 原文地址:https://www.cnblogs.com/coding-wtf/p/5768134.html
Copyright © 2011-2022 走看看