本文实现了二叉树的创建及其成员函数的实现
成员函数包括:
1)构造函数
2)拷贝构造函数
3)赋值运算符重载
4)先序遍历(先根遍历)(递归与非递归)
5)中序遍历(递归与非递归)
6)后序遍历(后根遍历)(递归与非递归)
7)层序遍历
8)节点个数
9)叶子节点个数
10)二叉树深度
11)查找二叉树节点
12)第k层节点的个数(两种方法)
二叉树的实现:
#pragma once
#include<iostream>
#include<assert.h>
#include<queue>
#include<stack>
using namespace std;
template<class T>
struct BinaryTreeNode
{
BinaryTreeNode(const T& d)
:_data(d)
,_left(NULL)
,_right(NULL)
{
}
T _data;//数据
BinaryTreeNode<T>* _left;//左孩子
BinaryTreeNode<T>* _right;//右孩子
};
template<class T>
class BinaryTree
{
typedef BinaryTreeNode<T> Node;
public:
BinaryTree(const T *a, const T& invalid, size_t size)//创建二叉树 invalid表示没有值(左孩子或右孩子为空)
:_root(NULL)
{
size_t index = 0;
_root = _CreatBinaryTree(a, invalid, size, index);//实现递归调用
}
BinaryTree()//默认构造函数
:_root(NULL)
{}
BinaryTree(const BinaryTree<T>& t)
:_root(NULL)
{
_root=_CopTree(t._root);
}
BinaryTree<T>& operator=(const BinaryTree<T>& t)
{
if (this != &t)
{
Node* root = _CopTree(t._root);
Destry(_root);
_root = root;
}
return *this;
}
~BinaryTree()
{
Destry(_root);
}
public:
Node* _CopTree(Node* root)
{
Node* head=NULL;
if (root)
{
head = new Node(root->_data);
head->_left = _CopTree(root->_left);
head->_right = _CopTree(root->_right);
}
return head;
}
//void PreOrder()//递归实现先序遍历
//{
// _PreOrder(_root);
// cout << endl;
//}
//void InOrder()//递归实现中