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

    /*二叉树前序、中序、层次层次遍历*/
    #include<stdio.h> #include<malloc.h> typedef char ElemType; typedef struct BiTNode { ElemType val; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; typedef struct LinkNode { BiTNode *data; struct LinkNode *next; }LinkNode; typedef struct { LinkNode *front,*rear; }LinkQueue; void InitQueue(LinkQueue &Q) //初始化队列 { Q.front=Q.rear=(LinkNode *)malloc(sizeof(LinkNode)); Q.front->next=NULL; } bool EmptyQueue(LinkQueue Q) //判断队列是否为空 { if(Q.rear==Q.front) return true; else return false; } void EnQueue(LinkQueue &Q,BiTree p) //树节点入队 { LinkNode *q; q=(LinkNode *)malloc(sizeof(LinkNode)); q->data=p; q->next=NULL; Q.rear->next=q; Q.rear=q; } bool DeQueue(LinkQueue &Q,BiTree &p) //树节点出队 { if(EmptyQueue(Q)) return false; LinkNode *q=Q.front->next; p=q->data; Q.front->next=q->next; if(Q.rear==q) Q.rear=Q.front; free(q); return true; } BiTree IniTree() //初始化树 { BiTree t; char ch; ch=getchar(); if(ch == '#') t=NULL; else { t=(BiTree)malloc(sizeof(BiTNode)); t->val=ch; t->lchild=IniTree(); t->rchild=IniTree(); } return t; } void visit(BiTree T) //访问树节点 { printf("%c",T->val); } bool proOrder(BiTree T) //先序遍历 { if(T==NULL) return false; else { visit(T); proOrder(T->lchild); proOrder(T->rchild); } return true; } bool inOrder(BiTree T) //中序遍历 { if(T==NULL) return false; else { inOrder(T->lchild); visit(T); inOrder(T->rchild); } } bool postOrder(BiTree T) //后序遍历 { if(T==NULL) return false; else { postOrder(T->lchild); postOrder(T->rchild); visit(T); } } void LevelOrder(BiTree T) //层次遍历 { LinkQueue Q; InitQueue(Q); BiTree p; if (T!=NULL) EnQueue(Q,T); //根节点入队 while(!EmptyQueue(Q)) { DeQueue(Q,p); //队头节点出队 visit(p); if(p->lchild!=NULL) EnQueue(Q,p->lchild); //左子树不空,左子树根节点入队 if(p->rchild!=NULL) EnQueue(Q,p->rchild); //右子树不空,右子树根节点入队 } } void main() { BiTree T; printf("按先序序列输入结点序列,'#'代表空: "); T=IniTree(); printf(" 先序遍历:"); proOrder(T); printf(" 中序遍历:"); inOrder(T); printf(" 后序遍历:"); postOrder(T); printf(" 层次遍历:"); LevelOrder(T); printf(" "); }
    /*感谢一位陌生大佬的帮助*/

      

  • 相关阅读:
    AS将一个项目导入到另一个项目中
    Android Studio出现:Cause: unable to find valid certification path to requested target
    小米手机Toast带app名称
    PopupWindow 点击外部区域无法关闭的问题
    EditText inputType类型整理
    Fragment通过接口回调向父Activity传值
    Android selector一些坑
    Installation failed with message Failed to commit install session 634765663 with command cmd package
    旷视上海研究院机器人方向招聘
    语义SLAM的数据关联和语义定位(四)多目标测量概率模型
  • 原文地址:https://www.cnblogs.com/-slz-2/p/13368424.html
Copyright © 2011-2022 走看看