递归输出二叉树的每个结点
来源:互联网 发布:sk2神仙水 知乎 编辑:程序博客网 时间:2024/05/06 01:04
算法导论:10.4-2 给定一个二叉树,写出一个 O(n) 时间的递归过程,将该树每个结点的关键字输出。
#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 + 1size_t pos_left = 2 * pos + 1;// 右子树坐标,右子树的坐标为 2 * pos + 2size_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
0 0
- 递归输出二叉树的每个结点
- 算法导论 10.4-3 输出二叉树的每个结点的关键字
- 求二叉树的每个结点的子孙数量
- 从上往下打印出二叉树的每个结点
- POJ 2499 求二叉树结点到根结点的路径长度 递归 二叉树
- 递归求解二叉树任意一结点的深度
- 从上到下,从左到右输出二叉树的结点
- 输出二叉树某一层的所有结点
- 输出二叉树中叶子结点的个数
- 二叉树中从根结点到叶子结点的所有路径(递归实现)
- 二叉树遍历输出的递归和非递归实现
- 输出二叉树中所有从根结点到叶子结点的路径
- 输出二叉树中所有从根结点到叶子结点的路径
- 输出二叉树中所有从根结点到叶子结点的路径
- 输出二叉树中随机两个结点的最小公共父结点
- 输出二叉树中中序遍历中给定结点的下一个结点
- 2.3从尾到头输出单链表每个结点的值
- c++输出二叉树叶子结点并输出叶子结点到根结点的路径长度
- Find a way out of the ClassLoader maze
- mysql 读写分离
- git 高级功能
- 112家IT公司薪水一览表(参考)
- java编程规范之java命名规范
- 递归输出二叉树的每个结点
- 深入Java关键字null
- 改写sys.stdout导致pycharm不能调试
- __FUNCTION__, __FILE__, __LINE__
- 利用sqlnet.ora限制IP访问
- HBase总结(十五)HBase数据恢复
- IP报文格式详解
- JS类的封装及实现代码(静态)
- 无法解析的外部符号