二叉树的创建
来源:互联网 发布:unity3d麻将开发思路 编辑:程序博客网 时间:2024/05/23 01:36
先序遍历:根左右:1->2->3->4->5->6->7->8
中序遍历:左根右:2->3->1->5->6->7->4->8
后序遍历:左右根:3->2->7->6->5->8->4->1
如何创建一个二叉树,采用自定义来定义每个结点的成员
采用递归的方式来创建一棵树根左右的方式,不断的进行递归来创建二叉树的左子树,右子树
例如这里举个例子创建如下的树
看它是怎么递归来创建的
#include<iostream>#include<stdlib.h>using namespace std;template<class T>struct BinaryTreeNode{ BinaryTreeNode( const T &data) : pLeft( NULL) , pRight( NULL) , _data( data) { } BinaryTreeNode<T >* pLeft; BinaryTreeNode<T >* pRight; T _data;};每个结点中包含自己的数据成员,还有指向该结点的左孩子的结点指针,指向该节点的右孩子的结点指针通过数组传参来构建二叉树template<class T>class BinaryTree{public: BinaryTree() //空树 :_pRoot( NULL) { } BinaryTree( const T arr[], size_t size ) { size_t index = 0; _CreatBinaryTree(_pRoot, arr, size , index); } void _CreatBinaryTree(BinaryTreeNode <T>*& pRoot, const T arr[], size_t size ,size_t& index ) { if (index < size&& arr[index ] != '#') { pRoot = new BinaryTreeNode<T >(arr[index]); _CreatBinaryTree( pRoot->pLeft, arr , size, ++index ); _CreatBinaryTree( pRoot->pRight, arr , size, ++index ); } } void Print_Front(BinaryTreeNode <T>* pRoot)//前序遍历二叉树 { BinaryTreeNode<T >* Cur = pRoot; //根左右 if (Cur) { cout <<Cur->_data << " "; Print_Front(Cur->pLeft); Print_Front(Cur->pRight); } } void Print_Middle(BinaryTreeNode <T>* pRoot)//中序遍历,左根右 { BinaryTreeNode<T >* Cur = pRoot; if (Cur) { Print_Middle(Cur->pLeft); cout << Cur->_data << " "; Print_Middle(Cur->pRight); } } void Print_Back(BinaryTreeNode <T>* pRoot) { BinaryTreeNode<T >* Cur = pRoot; if (Cur) { Print_Back(Cur->pLeft); Print_Back(Cur->pRight); cout << Cur->_data << " "; } }BinaryTreeNode<T >* _pRoot;};
其实递归的创建二叉树就是一层一层的进行函数的调用
二叉树的递归遍历分为:
前序遍历
中序遍历
后序遍历
在递归的前序遍历:就是先打印根节点在打印左子树节点然后右子树结点,
思想和递归的创建二叉树的思想是一致的。
0 0
- 二叉树的创建
- 二叉树的创建
- 二叉树的创建。
- 二叉树的创建
- 二叉树的创建
- 二叉树的创建
- 二叉树的创建
- 二叉树的创建
- 二叉树的创建
- 二叉树的 创建
- 二叉树的创建
- 二叉树的创建
- 数据结构【二叉树】 二叉树的创建
- 二叉树的二叉链表创建
- 二叉树的创建、遍历
- 完全二叉树的创建
- 平衡二叉树的创建
- 线索二叉树的创建
- Java文件流应用:复制文件
- hdu5971——Wrestling Match(以二分图判定为主要思路的多种搞法)
- linux下使用java编写redis测试案例
- 配置 maven 出现问题。Exception in thread "main" java.lang.NoClassDefFoundError:
- 连接github Permission denied (publickey).解决
- 二叉树的创建
- MAC-Mac OS Terminal 笔记1
- Unreal Open Day 2017 参会总结——NVIDA GameWorks 在UE4中的应用
- 关于双向队列
- Initializing a two dimensional std::vector
- 百度定位
- java中给出一个多线程TCP的ServerSocket例子?
- 【JavaScript】(6)Object、String、Array、Date对象的方法、属性(constructor、prototype)
- 深入PHP面向对象、模式与实践——企业模式