递归输出二叉树的每一个结点
2016-01-23 11:20
423 查看
算法导论:10.4-2 给定一个二叉树,写出一个 O(n) 时间的递归过程,将该树每一个结点的keyword输出。
#ifndef _BINARY_TREE_H_ #define _BINARY_TREE_H_ /***************************************************** 算法导论:10.4-2 一个二叉树,使用递归输出每一个结点 ******************************************************/ #include <iostream> template <class T> class BinaryTree; template <class T> class BinaryTree { public: class Node{ public: friend class BinaryTree < T >; T value; private: Node() :_parent(nullptr), _left(nullptr), _right(nullptr){} Node(const T& v) :_parent(nullptr), _left(nullptr), _right(nullptr), value(v){} Node* _parent; Node* _left; Node* _right; }; BinaryTree() :_root(nullptr){ } // 使用一个数组构造一个全然二叉树。给出数组的头指针和数组的长度 BinaryTree(T*, size_t); ~BinaryTree(); Node *getRoot()const{ return _root; } void print() const; private: // 二叉树的根结点 Node* _root; void freeNodes(const Node* root); void print(const Node*) const; void createTree(Node *root, T* a, size_t pos, size_t size); }; template <class T> BinaryTree<T>::BinaryTree(T* a, size_t size){ _root = new Node(a[0]); createTree(_root, a, 0, size); } template<class T> void BinaryTree<T>::createTree(Node *root, T* a, size_t pos, size_t size){ // 将数组中的元素依照顺序增加到二叉树中 // 左子树坐标,左子数的坐标为 2 * pos + 1 size_t pos_left = 2 * pos + 1; // 右子树坐标。右子树的坐标为 2 * pos + 2 size_t pos_right = pos_left + 1; // 创建根结点 if(pos_left < size){ // 创建左子树 root->_left = new Node(a[pos_left]); createTree(root->_left, a, pos_left, size); } if(pos_right < size){ // 创建右子树 root->_right = new Node(a[pos_right]); createTree(root->_right, a, pos_right, size); } } template <class T> BinaryTree<T>::~BinaryTree(){ // 释放全部结点所占空间 if (_root) freeNodes(_root); } template <class T> void BinaryTree<T>::freeNodes(const Node* root){ // 释放左孩子结点 if (root->_left) freeNodes(root->_left); // 释放右孩子结点 if (root->_right) freeNodes(root->_right); // 释放本结点 delete root; } template <class T> void BinaryTree<T>::print() const{ if (_root) { print(_root); } } template <class T> void BinaryTree<T>::print(const Node* root) const{ if(root){ std::cout << root->value << " "; print(root->_left); print(root->_right); } } #endif
相关文章推荐
- H3C防火墙出厂空配置管理口无法WEB登录
- 文章标题
- JavaScript define
- 【xv6学习之番外篇】详解struct Env 与 struct Trapframe
- hdu2050
- Android用户界面基础之TextView控件,EditText控件,Button控件的学习
- Session对象不必须依赖Cookie
- [乐意黎原创] 百度统计这个坑爹货
- eclipse安装activiti插件和基本使用
- 32位的win7和64位的win7要选择哪个呢?它们有什么区别?
- 5.6 array--高效的数值类型数组
- POJ 2243 - Knight Moves (A*)
- 从网上获取数据转换成byte[]数组
- 5.6 array--高效的数值类型数组
- Android使用系统签名以及安装
- initrd和initramfs 解析
- iOS开发实践之cell下载图片(SDWebImage)
- sql中exists,Intersect ,union 与union All的用法
- 树莓派2 B编译内核及安装
- ltnmp 3.0 发布,PHP 开发环境一键安装包