Sicily 1935 二叉树重建
来源:互联网 发布:石家庄网络电视台直播 编辑:程序博客网 时间:2024/05/16 13:45
数据结构的简单题,对帮助理解二叉树的遍历蛮有帮助的。
#include <iostream>#include <cstring>using namespace std;struct node{char val;node * left;node * right;};node * build(int n, char * pre, char * in){ //注意strchr返回的是指向那个字符的指针,要减去头指针 if (n <= 0) return NULL;node * ans = new node;ans->val = pre[0];int order = strchr(in, pre[0]) - in;ans->left = build(order, pre+1, in);ans->right = build(n-order-1, pre+order+1, in+order+1);//这里不能用[],要用指针的加减法 return ans;}void BFS(node * root){if (root == NULL) return;node* q[30];//q是输出序列 q[0] = root;int n = 0, o = 1;//n代表输出节点数,o代表总结点数 while (n < o){node * temp = q[n];n++;cout << temp->val;if (temp->left != NULL) q[o++] = temp->left;if (temp->right != NULL) q[o++] = temp->right;}}void deleteTree(node * root){if (root == NULL) return;if (root->left != NULL) deleteTree(root->left);if (root->right != NULL) deleteTree(root->right);delete root;}char preorder[30], inorder[30]; int main(){int t;cin >> t;while (t --){cin >> preorder >> inorder;int len = strlen(preorder);node * root = build(len, preorder, inorder);BFS(root);cout << endl; deleteTree(root);}return 0;}
0 0
- Sicily 1935 二叉树重建
- Sicily 1935 二叉树重建
- Sicily 1935. 二叉树重建
- Sicily 1935. 二叉树重建
- sicily 1935. 二叉树重建
- Sicily 1935. 二叉树重建
- [sicily]1935. 二叉树重建
- 1935 二叉树重建
- Sicily 1210 二叉树
- Sicily 1210. 二叉树
- sicily 1210 二叉树
- Sicily 1210(二叉树)
- Sicily 1210. 二叉树
- Sicily 1210 二叉树
- Sicily 1210. 二叉树
- Sicily 1210. 二叉树
- [sicily]1210. 二叉树
- sicily 1210. 二叉树
- Android中Invalidate和postInvalidate和requestLayout的区别
- 蜡烛线笔记语录
- 参照网上自己写了一个Ajax.js文件
- 67. Add Binary Leetcode Python
- uva10900(概率)
- Sicily 1935 二叉树重建
- unity3D之我用过的小玩意(二)
- 排列组合:poj 1496 Word Index+poj 1850 Code
- 让小米路由器变成一个聪明的WIFI(1):有人回家,它就发短信告诉你
- Best Time to Buy and Sell Stock II
- Python 的list 疑惑
- Fragment的setUserVisibleHint方法实现懒加载
- ZigZag Conversion
- Search