二叉树的建立和遍历
来源:互联网 发布:网络电视直播在线看 编辑:程序博客网 时间:2024/06/07 19:11
建立二叉树
#pragma once#include <iostream>#include <stdlib.h>#include <assert.h>#include <stack>#include <queue>using namespace std;template <class T>struct BinaryTreeNode{ BinaryTreeNode<T>* _left; BinaryTreeNode<T>* _right; T _data; BinaryTreeNode(const T& x) :_data(x) , _left(NULL) , _right(NULL) {}};template <class T>class BinaryTree{ typedef BinaryTreeNode<T> Node;public: //初始化 BinaryTree() :_root(NULL) {} //构造 BinaryTree(T* arr, size_t _size, const T& invalid) { assert(arr); size_t index = 0; _root=_creatTree(arr, _size, index, invalid); } //拷贝构造 BinaryTree(BinaryTree<T>& x) { _root = _CopyBinaryTree(x._root); } //运算符重载:判断两个树是否相等 BinaryTree<T>& operator=(BinaryTree<T>& x) { if (*this != x) { Node* tmp = _CopyBinaryTree(x._root); _Distory(_root); _root = tmp; } return *this; } //析构 ~BinaryTree() { Distory(); } //前序遍历(递归) PrevOrder() { cout << "前序遍历二叉树/n"; _PrevOrder(_root) cout << endl; } //中序遍历(递归) InOrder() { _InOrder(_root); cout << endl; } //后序遍历(递归) //层序遍历 //前序遍历(非递归) //中序遍历(非递归) //后序遍历(非递归)protected: Node* _creatTree(const T* arr, size_t size, const T& invalid, size_t index) { Node* root = NULL; while (arr[index] != invalid&& index < size) { root = new Node(arr[index]); root->_left = _creatTree(arr, size, invalid, ++index); root->_right = _creatTree(arr, size, invalid, ++index); } return root; } void Distory() { _Distory(_root); _root = NULL; } void _Distory(Node* root) { if (root == NULL) return; _Distory(root->_left); _Distory(root->_right); delete root; } // Node* _CopyBinaryTree(Node* root) { if (root == NULL) { return 0; } Node* node = new Node(root->_data); node->_left = _CopyBinaryTree(root->_left); node->_right = _CopyBinaryTree(root->_right); return node; }protected: Node *_root;};
关于遍历和节点查找明天再写啦
阅读全文
0 0
- 二叉树的建立和遍历
- 二叉树 普通的 建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- Tree 二叉树的建立 和遍历
- 二叉树的建立和遍历
- [转]二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历算法
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 二叉树的建立和遍历
- 线索二叉树的建立和遍历
- 端口的状态详解
- linux命令学习与理解
- java基础知识--IO篇
- I2C 时序详解,精确到每一个时钟
- struts2入门,从下载到简单的配置
- 二叉树的建立和遍历
- 面试问题待解答
- FPGA中SRL16资源
- 如何理解beta分布
- Linux下安装部署Redis
- jQuery之ajax函数的一个小例子
- 【转】JVM调优总结(九)-新一代垃圾回收算法
- 【stm32f407】SD协议(二)-SD卡
- POJ 1410 Intersection(判断线段交和点在矩形内)