标签:Node Binary 遍历 int 二叉树 rchild now root lchild
#include <bits/stdc++.h> #include <stdio.h> #include <stdlib.h> #include <queue> using namespace std; const int maxn = 110; struct node{ int lchild,rchild; }Node[maxn]; bool notRoot[maxn] = {false};//记录是否不是根节点,初始均是根节点 int n,num = 0;//n为节点个数,num为当前已经输出的节点个数 //print函数输出节点id的编号 void print(int id){ printf("%d",id); num++; if(num < n)printf(" "); else printf("\n"); } //中序遍历 void inOrder(int root){ if(root == -1){ return; } inOrder(Node[root].lchild); print(root); inOrder(Node[root].rchild); } //层序遍历 void BFS(int root){ queue<int> q; q.push(root); while(!q.empty()){ int now = q.front(); q.pop(); print(now); if(Node[now].lchild != -1) q.push(Node[now].lchild); if(Node[now].rchild != -1) q.push(Node[now].rchild); } } //后序遍历 void postOrder(int root){ if(root == -1){ return; } postOrder(Node[root].lchild); postOrder(Node[root].rchild); swap(Node[root].lchild,Node[root].rchild); } int strToNum(char c){ if(c == '-'){ return -1; } else{ notRoot[c-'0'] = true; return c- '0';//返回节点编号 } } int findRoot(){ for(int i =0;i<n;++i){ if(notRoot[i] == false){ return i; } } } int main(){ char lchild,rchild; scanf("%d",&n); for(int i=0;i<n;++i){ scanf("%*c%c %c",&lchild,&rchild); Node[i].lchild = strToNum(lchild); Node[i].rchild = strToNum(rchild); } int root = findRoot(); postOrder(root); BFS(root); num = 0; inOrder(root); system("pause"); return 0; }
标签:Node,Binary,遍历,int,二叉树,rchild,now,root,lchild 来源: https://www.cnblogs.com/JasonPeng1/p/12232351.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。