各种方法建立二叉树
2016-05-25 20:14
375 查看
各种方法建立二叉树
//非递归建立二叉树 struct node{ char data; node* left; node* right; }; void createtree() { node* q; node* tree[max]; int i, j; char val; node* root = NULL; cin >> i >> val; while (i != 0&& val != '#') { //输入结束标志 q = new node; q->data = val; q->left = NULL; q->right = NULL; tree[i] = q; if (i == 1) { root = q; } else { j = i/2; if (i%2 == 0) { tree[j]->left = q; } else { tree[j]->right = q; } } cin >> i >> val; } } //队列建立二叉树 BinaryTree(vector<char> & a) { // 将vector中的数据构建成二叉树 node* root; if (a.empty()) { root = NULL; return; } else { std::queue<Node**> queue_node; root = new Node(a[0]); queue_node.push(&root->left); queue_node.push(&root->right); int i = 1; int n = a.size(); while (i < n) { Node** temp = queue_node.front(); queue_node.pop(); if (i >= a.size()) { temp = NULL; i++; } else { *temp = new Node(a[i]); queue_node.push(&((*temp)->left)); queue_node.push(&((*temp)->right)); i++; } } } } //递归建立二叉树 void creat_tree(node* &root) { char ch; cin >> ch; if (ch == '0') { // 代表子节点为空 root = NULL; } else { root = new node; root->data = ch; creat_tree(root->lchild); creat_tree(root->rchild); } }
相关文章推荐
- hdu 1576(逆元)
- 【转】Mongodb的基本使用总结
- ImageLoder配置步骤
- Hibernate中SQL标量查询、实体查询
- Codeforces 612C Replace To Make Regular Bracket Sequence
- Work Applications编程题:最大异或值
- 2016.5.24——Intersection of Two Linked Lists
- POJ 2478 Farey Sequence
- iOS开发中(null)与<null>的处理
- 【转】Java生产者消费者模式的实现的几种方法
- 蓝桥杯C++B组历届决赛真题
- hdu 3652 数位dp(能被13整除且包含13的数的个数)
- poj 1328 贪心经典
- Java 单例模式
- ImageLoader
- linux创建进程消耗内存
- Nosql Mongodb 并发控制之乐观锁
- CDN基础服务-防盗链
- 制作按钮点击的平滑的过渡效果
- 2016年5月25日下午(妙味课堂js预热课程-4笔记二)