二叉树的遍历
来源:互联网 发布:php网站破解工具 编辑:程序博客网 时间:2024/06/04 01:11
包括二叉树的递归前、中、后序,以及非递归前序
#include<iostream>
#include<cstdio>#include<cstdlib>
#include<cstring>
using std::cin;
using std::cout;
using std::endl;
//using std::stack;
using namespace std;
typedef struct BTNode
{
char data;
BTNode *lchild;
BTNode *rchild;
}BTNode;
void PreRecurTraversal(BTNode *bt)//先序递归
{
if(bt != NULL)
{
cout<<bt->data<<" ";
PreRecurTraversal(bt->lchild);
PreRecurTraversal(bt->rchild);
}
}
void MidRecurTraversal(BTNode *bt)//中序递归
{
if(bt != NULL)
{
MidRecurTraversal(bt->lchild);
cout<<bt->data<<" ";
MidRecurTraversal(bt->rchild);
}
}
void PostRecurTraversal(BTNode *bt)//后序递归
{
if(bt != NULL)
{
MidRecurTraversal(bt->lchild);
MidRecurTraversal(bt->rchild);
cout<<bt->data<<" ";
}
}
/*void PreTraversalOne(BTNode *bt)//前序非递归遍历
{
BTNode *pbt = bt;
std::stack<BTNode*> s;
while(!s.empty()|| pbt != NULL)
{
while(pbt != NULL)
{
cout<<pbt->data;
s.push(pbt);
pbt = pbt->lchild;
}
if(!s.empty())
{
pbt = s.top();
s.pop();
pbt = pbt->rchild;
}
}
}*/
BTNode* createBTNode() //建立二叉树
{
char c;
BTNode* bt = NULL;
if((c = getchar()) == ',')
bt = NULL;
else
{
bt = (BTNode*)malloc(sizeof(BTNode));
bt->data = c;
bt->lchild = createBTNode();
bt->rchild = createBTNode();
}
return bt;
}
int TreeDepth(BTNode* pRoot)
{
if(pRoot == NULL)
return 0;
int nLeft = TreeDepth(pRoot->lchild);
int nRight = TreeDepth(pRoot->rchild);
return (nLeft > nRight) ? (nLeft + 1) : (nRight + 1);
}
int main()
{
BTNode * bt = NULL;
bt = createBTNode();
PreRecurTraversal(bt);
cout<<TreeDepth(bt)<<endl;
return 0;
}
0 0
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- iOS UITextField属性全解
- Flash Builder 4:进程意外终止。 application descriptor not found 启动命令详细信息:
- oracle 使用leading, use_nl, rownum调优
- shell 中的单引号和双引号
- spark internal - 作业调度
- 二叉树的遍历
- christian louboutin men and Deng Deng Jiaying expressed the hope that the idea of � oing his girl
- [小技巧] Notepad++关闭拼写检查
- tiffany outlet italia CD action
- abercrombie outlet causing the school attention. 16
- OC中6种多线程的使用方式
- qmake的使用简介
- python使用matplotlib绘图 -- barChart
- Linux下select, poll和epoll IO模型的详解