zoukankan      html  css  js  c++  java
  • 二叉树建立和遍历

    二叉树创建遍历规则:

    1.先序:根-左-右

    2.中序:左-根-右

    3.后序:左-右-根


    二叉树定义和辅助函数例如以下:

    struct node {  
        int data;  
        struct node* left;  
        struct node* right;  
    };  
      
    void visit(int data)  
    {  
        printf("%d ", data);  
    }  
    
    int indata()
    {
        int data;
        scanf("%d",&data);
        return data;
    }




    先序创建二叉树:

    struct node* CreateBiTree()//先序建立一个二叉树  
    {   
        char x; //x为根节点  
        struct node* t;   
        x=indata();  
        if (x==' ') /* 推断当前子树是否创建完毕*/   
            return NULL;   
        else   
        {   
            t=(struct node*)malloc(sizeof(struct node));   
            t->data=x;   
            t->left=CreateBiTree();   
            t->right=CreateBiTree();   
        }   
        return t;  
    }  
    先序遍历二叉树:

    void preOrder(struct node* root)  
    {  
        if (root == NULL)  
            return;  
        visit(root->data);  
        preOrder(root->left);  
        preOrder(root->right);  
    }  
    



    中序创建二叉树:

    struct node* CreateBiTree()//先序建立一个二叉树  
    {   
        char x; //x为根节点  
        struct node* t;   
        x=indata();  
        if (x==' ') /* 推断当前子树是否创建完毕*/   
            return NULL;   
        else   
        {  
            t=(struct node*)malloc(sizeof(struct node)); 
            t->left=CreateBiTree();  
            t->data=x;     
            t->right=CreateBiTree();   
        }   
        return t;  
    }  
    中序遍历二叉树:

    void inOrder(struct node* root)  
    {  
        if (root == NULL)  
            return;  
        inOrder(root->left);  
        visit(root->data);  
        inOrder(root->right);  
    }  




    后序创建二叉树

    struct node* CreateBiTree()//先序建立一个二叉树  
    {   
        char x; //x为根节点  
        struct node* t;   
        x=indata();  
        if (x==' ') /* 推断当前子树是否创建完毕*/   
            return NULL;   
        else   
        {  
            t=(struct node*)malloc(sizeof(struct node)); 
            t->left=CreateBiTree();    
            t->right=CreateBiTree();   
        	t->data=x;   
        }   
        return t;  
    }  
    
    后序遍历二叉树

    void inOrder(struct node* root)  
    {  
        if (root == NULL)  
            return;  
        inOrder(root->left);   
        inOrder(root->right);  
        visit(root->data); 
    }  



    转载请注明作者:小刘





  • 相关阅读:
    基于Python的人脸动漫转换
    let 与 var的区别
    【LeetCode】汇总
    【HDU】4632 Palindrome subsequence(回文子串的个数)
    【算法】均匀的生成圆内的随机点
    【LeetCode】725. Split Linked List in Parts
    【LeetCode】445. Add Two Numbers II
    【LeetCode】437. Path Sum III
    【LeetCode】222. Count Complete Tree Nodes
    【LeetCode】124. Binary Tree Maximum Path Sum
  • 原文地址:https://www.cnblogs.com/jhcelue/p/7264331.html
Copyright © 2011-2022 走看看