二叉树的先序建立、遍历、镜像、节点数、深度的具体代码实现
输出:
更多内容请访问 IT部落格(http://www.itbuluoge.com)
实现代码(VC6.0编译通过):
#include <iostream>
#include <queue>
using namespace std;
//二叉树节点定义
class Node
{
public:
char value;
Node* lchild;
Node* rchild;
};
//先序创建二叉树 输入先序遍历的字符顺序 例如 ab###
void CreateTree(Node* &tree)
{
char ch;
scanf("%c",&ch);
if(ch=='#')tree=NULL;
else
{
tree=new Node();
tree->value=ch;
CreateTree(tree->lchild);//递归创建左子树
CreateTree(tree->rchild);//递归创建右子树
}
}
//先序遍历
void preorder(Node* tree)
{
if(tree!=NULL)
{
cout<<tree->value;
preorder(tree->lchild);
preorder(tree->rchild);
}
}
//中序遍历
void midorder(Node* tree)
{
if(tree!=NULL)
{
preorder(tree->lchild);
cout<<tree->value;
preorder(tree->rchild);
}
}
//后序遍历
void latorder(Node* tree)
{
if(tree!=NULL)
{
preorder(tree->lchild);
preorder(tree->rchild);
cout<<tree->value;
}
}
//层序遍历
void grade(Node* tree)
{
queue<Node*> myque;
//根节点不为空,先进队列
if(tree!=NULL)
{
myque.push(tree);
}
//如果队列不空,则继续
while(!myque.empty())
{
Node* temp=myque.front();
myque.pop();
//左子树不空,则进队列
if(temp->lchild)myque.push(temp->lchild);
//右子树不空,则进队列
if(temp->rchild)myque.push(temp->rchild);
cout<<temp->value<<" ";
}
}
//二叉树的镜像
void mirror(Node* tree)
{
if(tree!=NULL)
{
Node* temp;
temp=tree->lchild;
tree->lchild=tree->rchild;
tree->rchild=temp;
//交换左子树
mirror(tree->lchild);
//交换右子树
mirror(tree->rchild);
}
}
//二叉树节点数
int count(Node* tree)
{
if(tree==NULL)return 0;
return count(tree->lchild)+count(tree->rchild)+1;
}
//二叉树深度
int deep(Node* tree)
{
if(tree==NULL)return 0;
return deep(tree->lchild)>deep(tree->rchild)?deep(tree->lchild)+1:deep(tree->rchild)+1;
}
int main()
{
Node* root;
CreateTree(root);
cout<<"先序遍历:";
preorder(root);
cout<<endl;
cout<<"中序遍历:";
midorder(root);
cout<<endl;
cout<<"后序遍历:";
latorder(root);
cout<<endl;
cout<<"层序遍历:";
grade(root);
cout<<endl;
cout<<"镜像:";
mirror(root);
preorder(root);
cout<<endl;
cout<<"节点数:";
cout<<count(root);
cout<<endl;
cout<<"树深度:";
cout<<deep(root);
return 0;
}
输出:
更多内容请访问 IT部落格(http://www.itbuluoge.com)