中途对于递归总是理不清,后来看了代码和书才想通:
递归==递+归:必须要有递归结束条件,可以不是返回值,若调用一个递归的主算法为第0层算法,则从主算法调用递归算法为进入第1层调用,从第i层递归调用本算法为进入第i+1层,反之,退出第i层递归调用,则返回至第i-1层调用,简单讲:就是当第i+1层达到了递归结束条件,就会回到第i层递归(当时一直认为直接执行到第i+1层,就不再返回了。呵呵),为了保证递归调用正确执行,系统要建立递归调用工作栈。每一层递归调用所需的信息构成一个工作记录,其中,包括所有实参指针,所有局部变量以及返回上一层的地址
#include<iostream>
using namespace std;
template<class T>
struct BinaryTreeNode
{
BinaryTreeNode* _left;
BinaryTreeNode* _right;
T _data;
BinaryTreeNode(const T& x)
:_left (NULL)
,_right (NULL)
,_data (x)
{}
};
template<class T>
class BinaryTree
{
public:
BinaryTree()
:_root(NULL)
{}
BinaryTree(const T* a,size_t size)
{
size_t index = 0;
_root = _CreateTree(a,size,index);//构建树
}
BinaryTree (const BinaryTree<T>& s)
:_root ->_left(s._root ->_left )
,_root ->_right(s._root ->_right )
,_root ->_data(s._root ->_data )
{
s._root ->_left = NULL;
s._root ->_right = NULL;
}
size_t size()
{
return _size(_root);
}
size_t Depth()
{
return _Depth(_root);
}
size_t leafSize()
{
return _leafSize(_root);
}
void prevorder()//前序遍历《根左右》
{
_prevorder(_root);
cout <<endl;
}
void Inorder()//中序遍历《左根右》
{
_Inorder(_root);
cout<<endl;
}
void postorder()//后序遍历《左右根》
{
_postorder(_root);
cout<<endl;
}
public:
BinaryTreeNode<T>* _CreateTree(const T* a,size_t size,size_t& index)
{
BinaryTreeNode<T>* root = NULL;
if(a[index] != '#'&& index < size)
{
root = new BinaryTreeNode<T>(a[ index ]);//创建树节点
root->_left = _CreateTree(a,size,++index);
root->_right = _CreateTree(a,size,++index);
}
return root;
}
size_t _size(BinaryTreeNode<T>* root)//节点个数
{
if(root == NULL)
{
return 0;
}
return (_size( root->_left ))+(_size ( root->_right ))+1;//每递归一次都加上他的上个节点,也就是根节点。所以只加一
}
size_t _Depth(BinaryTreeNode<T>* root)//树的深度
{
if(root == NULL)
return 0;
size_t a = _Depth (root->_left )+1;
siez_t b = _Depth (root->_right)+1;
return a>b?a:b;
}
size_t _leafSize(BinaryTreeNode<T>* root) //叶个数
{
if(root == NULL)
return 0;
else if(root->_left ==NULL && root->_right == NULL )
return 1;
else
return _leafSize(root ->_left)+_leafSize (root->_right );
}
void _prevorder(BinaryTreeNode<T>* root)
{
if(root == NULL)
return ;
cout<<root->_data <<" ";
_prevorder(root->_left );
_prevorder(root->_right );
}
void _Inorder(BinaryTreeNode<T>* root)
{
if(root != NULL)
{
_Inorder(root->_left );
cout<<root->_data <<" ";
_Inorder(root->_right );
}
}
void _postorder(BinaryTreeNode<T>* root)
{
if(root != NULL )
{
_postorder(root->_left );
_postorder(root->_right );
cout<<root->_data <<" ";
}
}
protected:
BinaryTreeNode<T>* _root;
};
int main()
{
int a1[9]={1,2,3,'#',4,'#','#',5, 6};
int a2[15] = {1,2,'#',3,'#','#',4,5,'#',6,'#',7,'#','#',8};
BinaryTree<int> bt(a1,9);
bt.prevorder ();
bt.Inorder ();
bt.postorder ();
return 0;
}