日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

九度oj 1523 从上往下打印二叉树

發布時間:2024/4/14 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 九度oj 1523 从上往下打印二叉树 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

原題鏈接:http://ac.jobdu.com/problem.php?pid=1523

建樹,再層次遍歷bfs。為了找根方便些,加了father指針。。。

如下:

1 #include<algorithm> 2 #include<iostream> 3 #include<cstdlib> 4 #include<cstring> 5 #include<cstdio> 6 #include<vector> 7 #include<queue> 8 using std::queue; 9 using std::vector; 10 using std::cin; 11 const int Max_N = 1100; 12 struct Node{ 13 int v; 14 Node *f, *ch[2]; 15 inline void set(int _v = 0, Node *p = NULL){ 16 v = _v, f = ch[0] = ch[1] = p; 17 } 18 inline void link(Node *x, bool d){ 19 ch[d] = x; 20 x->f = this; 21 } 22 }; 23 struct BinaryTree{ 24 Node *tail, *root, *null; 25 Node stack[Max_N], *ptr[Max_N]; 26 void init(){ 27 tail = &stack[0]; 28 null = tail++; 29 null->set(); 30 root = null; 31 } 32 inline Node *newNode(int v){ 33 Node *p = tail++; 34 p->set(v, null); 35 return p; 36 } 37 inline void gogo(int n){ 38 char c; 39 int i, v, a, b; 40 for (i = 1; i <= n; i++){ 41 scanf("%d", &v); 42 ptr[i] = newNode(v); 43 } 44 for (i = 1; i <= n; i++){ 45 cin >> c; 46 if (c == 'd'){ 47 scanf("%d %d", &a, &b); 48 ptr[i]->link(ptr[a], 0); 49 ptr[i]->link(ptr[b], 1); 50 } else if (c == 'l'){ 51 scanf("%d", &a); 52 ptr[i]->link(ptr[a], 0); 53 } else if (c == 'r'){ 54 scanf("%d", &b); 55 ptr[i]->link(ptr[b], 1); 56 } else { 57 ; 58 } 59 if (ptr[i]->f == null) root = ptr[i]; 60 } 61 } 62 inline void bfs(){ 63 queue<Node *> que; 64 vector<int> ans; 65 que.push(root); 66 while (!que.empty()){ 67 Node *x = que.front(); 68 que.pop(); 69 ans.push_back(x->v); 70 if (x->ch[0] != null) que.push(x->ch[0]); 71 if (x->ch[1] != null) que.push(x->ch[1]); 72 } 73 int n = ans.size(); 74 for (int i = 0; i < n; i++){ 75 printf("%d%c", ans[i], i < n - 1 ? ' ' : '\n'); 76 } 77 } 78 }tree; 79 int main(){ 80 #ifdef LOCAL 81 freopen("in.txt", "r", stdin); 82 freopen("out.txt", "w+", stdout); 83 #endif 84 int n; 85 while (~scanf("%d", &n)){ 86 tree.init(), tree.gogo(n), tree.bfs(); 87 } 88 return 0; 89 } View Code

?

轉載于:https://www.cnblogs.com/GadyPu/p/4477606.html

總結

以上是生活随笔為你收集整理的九度oj 1523 从上往下打印二叉树的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。