上篇咱们说到二叉树的一种建立方法及三种遍历方法的递归非递归算法。这篇换了一种新的建立方法,用先根遍历递归的思路建立二叉树,用递归的方法计算深度,用中根递归和非递归方法遍历整个二叉树。
BinaryTree.h
//二叉树的建立和遍历
#ifndef BINARYTREE_H_
#define BINARYTREE_H_
#include <iostream>
typedef int T;
struct Node
{
T data;
Node *lch;
Node *rch;
};
class BinaryTree
{
private:
Node *root;
Node *create_bt();
void inorder(Node *p);
int predepth(Node *t);
void destroy(Node *p);
int max(int x, int y);
public:
BinaryTree()
{
root=NULL;
}
~BinaryTree()
{
destroy(root);
}
void create();
void inorder()
{
inorder(root);
}
void inorderz();//中根非递归遍历
int predepth(){return predepth(root);}//求二叉树的深度递归函数
};
#endifBinaryTree.cpp
#include "BinaryTree.h"
#include <iostream>
#include <stack>
using namespace std;
void BinaryTree::create()
{
cout<<"请按照二叉树先根次序,且将空孩子置为0,组织数据"<<endl;
cout<<"每次输入结点的数据,假设是一棵3个结点的满二叉树。"<<endl;
cout<<"那么输入应是:11 22 0 0 33 0 0"<<endl;
root=create_bt();
}
Node *BinaryTree::create_bt()
{
Node *t;
int e;
cout<<"输入结点的值:";
cin>>e;
if(e==0)
t=NULL;
else
{
t=new Node;
t->data=e;
t->lch=create_bt();
t->rch=create_bt();
}
return t;
}
void BinaryTree::inorderz()//中根非递归遍历
{
Node *p=root;
Node *q;
stack<Node *> S;
do
{
while(p!=NULL)
{
S.push(p);
p=p->lch;
}
p=S.top();
S.pop();
cout<<p->data<<" ";
p=p->rch;
}while(!(S.empty() && p==NULL));
}
void BinaryTree::inorder(Node *p)
{
if(p!=NULL)
{
inorder(p->lch);
cout<<p->data<<" ";
inorder(p->rch);
}
}
int BinaryTree::predepth(Node *t)
{
if(t!=NULL)
{
return 1+max(predepth(t->lch),predepth(t->rch));
}
else
return 0;
}
int BinaryTree::max(int x, int y)
{
return (x>=y?x:y);
}
//用递归法删除二叉树的所有结点
void BinaryTree::destroy(Node *p)
{
if(p!=NULL)
{
destroy(p->lch);
destroy(p->rch);
}
delete p;
}
main.cpp
#include <iostream>
#include "BinaryTree.h"
using namespace std;
int main()
{
BinaryTree BT;
BT.create();
cout<<"中根递归遍历:"<<endl;
BT.inorder();
cout<<"中根非递归遍历:"<<endl;
BT.inorderz();
cout<<endl<<"二叉树的深度为:"<<BT.predepth()<<endl;
system("pause");
return 0;
}结果为:
原文:http://blog.csdn.net/jiang111_111shan/article/details/46431827