一、二叉树的创建:
首先,二叉树的创建常见的有根据先序遍历(虚空结点)、后序遍历(虚空结点)和层次遍历(虚空结点)三种方法 + 根据先序和中序遍历创建二叉树、根据中序和后序遍历创建二叉树。
方法一:通过使用模板构建二叉树。(根据先序或后序创建二叉树)
#pragma once
#include<iostream>
using namespace std;
template<typename T>class BinTree;
template<typename T>
class Node
{
friend class BinTree<T>;
public:
Node() :_data(T()), _leftchild(nullptr), _rightchild(nullptr)
{}
Node(T x) :_data(x), _leftchild(nullptr), _rightchild(nullptr)
{}
~Node()
{}
private:
T _data;
Node<T> *_leftchild;
Node<T> *_rightchild;
};
template<typename T>
class BinTree
{
public:
BinTree() :_root(nullptr)
{}
///
void CreateTree()
{
CreateTree(_root);
}
void CreateTree(T *x, int n)
{
int i = n - 1;
CreateTree(_root, x, i);
}
//根据先序遍历创建二叉树
void CreateTree(Node<T> *&x)
{
T a;
cin >> a;
if (a == '#')
return;
else
{
x = new Node<T>(a);
CreateTree(x->_leftchild);
CreateTree(x->_rightchild);
}
}
//根据后序遍历创建二叉树
void CreateTree(Node<T> *&y, T *x, int &i)
{
if (x[i] == '#')
return;
else
{
y = new Node<T>(x[i]);
CreateTree(y->_rightchild, x, --i);
CreateTree(y->_leftchild, x, --i);
}
}
///
~BinTree()
{}
private:
Node<T> *_root;
};
方法二:直接使用结构体:
#pragma once
#include <vector>
#include <iostream>
using namespace std;
typedef int DataType;
struct BinaryNode
{
BinaryNode* _left;
BinaryNode* _right;
DataType _data;
BinaryNode(DataType x)
:_left(NULL)
,_right(NULL)
,_data(x)
{}
};
void CreateBinaryTree(BinaryNode*& root,
const vector<DataType>& datas,
int& i)
{
// 前序遍历构建二叉树
if (root == NULL && i < datas.size() && datas[i] != '#')
{
root = new BinaryNode(datas[i]);
CreateBinaryTree(root->_left, datas, ++i);
CreateBinaryTree(root->_right, datas, ++i);
}
}
二、二叉树的4种遍历
//先序遍历
void PreOrder()
{
PreOrder(_root);
}
void PreOrder(Node<T> *root)
{
if (root != nullptr)
{
cout << root->_data << " ";
PreOrder(root->_leftchild);
PreOrder(root->_rightchild);
}
}
//中序遍历
void MidOrder()
{
MidOrder(_root);
}
void MidOrder(Node<T> *root)
{
if (root != nullptr)
{
MidOrder(root->_leftchild);
cout << root->_data << " ";
MidOrder(root->_rightchild);
}
}
//后序遍历
void PosOrder()
{
PosOrder(_root);
}
void PosOrder(Node<T> *root)
{
if (root != nullptr)
{
PosOrder(root->_leftchild);
PosOrder(root->_rightchild);
cout << root->_data << " ";
}
}
//层次遍历
void LevelOrder()
{
LevelOrder(_root);
}
void LevelOrder(Node<T>* root)
{
queue<Node<T> *> s;
Node<T> *temp;
s.push(root);
while (s.size() != 0)
{
temp = s.front();
s.pop();
cout << temp->_data << " ";
if (temp->_leftchild != nullptr)
s.push(temp->_leftchild);
if (temp->_rightchild != nullptr)
s.push(temp->_rightchild);
}
}