zoukankan      html  css  js  c++  java
  • c++ 二叉树的遍历

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    #include <ctype.h>
    #include <stdarg.h> 
    #include <time.h>
    struct node
    {
        long  data; //存放数据的一个或者多个项 
        long count;
        struct node *pLeft;  //左孩子 指向一个二叉树
        struct node *pRight; //右孩子  指向一个二叉树
    };
    
    struct node * CreateNode(long value)
    {
        struct node *p=malloc(sizeof(struct node));
        p->pLeft=p->pRight=NULL;
        p->data=value;
        p->count=1;
    }
    struct node * AddNode(struct node * pNode,long v)
    {
        //情况一 pNode==NULL
        if (pNode==NULL)
        {
            return CreateNode(v);
        }
        // pNode->data=v
        if (pNode->data==v)
        {
            pNode->count++;
            return pNode;
        }
        //v大于结点数据
        if (v>pNode->data)
        {
            if (pNode->pRight==NULL)
            {
                pNode->pRight=CreateNode(v);
                return pNode->pRight;
            }else return AddNode(pNode->pRight,v); //递归调用
        }
        //v小于 结点数据
        if (v<pNode->data)
        {
            if (pNode->pLeft==NULL)
            {
                pNode->pLeft=CreateNode(v);
                return pNode->pLeft;
            }else return AddNode(pNode->pLeft,v); //递归调用
        }
    
        return NULL;
    }
    void traversal(struct node* pNode)
    { int i;
        if (pNode->pLeft!=NULL)
        {
            traversal(pNode->pLeft);
        }
        for (i=1;i<=pNode->count;i++)
        {
            printf("%d,",pNode->data);
        }
        if (pNode->pRight!=NULL)
        {
                traversal(pNode->pRight);
        }
    
        
    
    }
    int main(void)
    {    
        struct node*root;
        long v,i;
        printf("请输入二叉树根结点数值:");
        scanf("%d",&v);
        root=CreateNode(v); //根结点
        for (i=0;i<=10;i++)
        {
            AddNode(root,i);
        }
     //遍历
        traversal(root);
        getchar();
        getchar();
        getchar();
        return 0;
    }
  • 相关阅读:
    asp.net core 3.1 源码学习(二)
    asp.net core 3.1 源码学习(一)
    netcore3.0 IHost 源码解析(二)
    netcore3.0 IHost 源码解析(一)
    netcore3.0 Logging 日志系统(三)
    netcore3.0 Logging 日志系统(二)
    netcore3.0 Logging 日志系统(一)
    netcore3.0 IOptions 选项(二)
    Nginx使用记录
    SC Create 创建一个Windows系统服务 转
  • 原文地址:https://www.cnblogs.com/whzym111/p/6145495.html
Copyright © 2011-2022 走看看