// bit.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
/*
a
/ \
b c
/\ /
e f g
*/
// 先序创建顺序:abe##f##cg###
#include <stack>
#include <iostream>
struct bite
{
char data;
struct bite* left;
struct bite* right;
bite()
{
left = NULL;
right = NULL;
}
};
struct bite * create(void)// 创建先序二叉树,最终返回根结点指针
{
struct bite *root;
char a;
std::cin>>a;
if ('#'==a)
{
root = NULL;
}
else
{
root = new bite;
root->data = a;
root->left = create();
root->right = create();
}
return root;
}
void visit(char a)
{
printf("%c\t",a);
}
void preInterverse(struct bite* T,void(*pFun)(char))// 递归遍历先序二叉树
{
if (T)
{
pFun(T->data);
if (T->left)
{
preInterverse(T->left,pFun);
}
if (T->right)
{
preInterverse(T->right,pFun);
}
}
}
void preInterverseNo(struct bite* T,void(*pFun)(char))// 非递归遍历先序二叉树
{
std::stack<struct bite> s;
struct bite* p = T;
while (p || !s.empty())
{
if (p)
{
pFun(p->data);
s.push(*p);
p = p->left;
}
else
{
if (!s.empty())
{
struct bite& m=s.top();// 返回栈顶元素引用
s.pop();
p = m.right;
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
struct bite* b = create();
preInterverse(b,visit);
printf("\n");
preInterverseNo(b,visit);
return 0;
}
/*
std::stack<struct bite> s;
struct bite * p=NULL;
*p = s.top();//错误,s.top()只能返回引用
*/
//
#include "stdafx.h"
/*
a
/ \
b c
/\ /
e f g
*/
// 先序创建顺序:abe##f##cg###
#include <stack>
#include <iostream>
struct bite
{
char data;
struct bite* left;
struct bite* right;
bite()
{
left = NULL;
right = NULL;
}
};
struct bite * create(void)// 创建先序二叉树,最终返回根结点指针
{
struct bite *root;
char a;
std::cin>>a;
if ('#'==a)
{
root = NULL;
}
else
{
root = new bite;
root->data = a;
root->left = create();
root->right = create();
}
return root;
}
void visit(char a)
{
printf("%c\t",a);
}
void preInterverse(struct bite* T,void(*pFun)(char))// 递归遍历先序二叉树
{
if (T)
{
pFun(T->data);
if (T->left)
{
preInterverse(T->left,pFun);
}
if (T->right)
{
preInterverse(T->right,pFun);
}
}
}
void preInterverseNo(struct bite* T,void(*pFun)(char))// 非递归遍历先序二叉树
{
std::stack<struct bite> s;
struct bite* p = T;
while (p || !s.empty())
{
if (p)
{
pFun(p->data);
s.push(*p);
p = p->left;
}
else
{
if (!s.empty())
{
struct bite& m=s.top();// 返回栈顶元素引用
s.pop();
p = m.right;
}
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
struct bite* b = create();
preInterverse(b,visit);
printf("\n");
preInterverseNo(b,visit);
return 0;
}
/*
std::stack<struct bite> s;
struct bite * p=NULL;
*p = s.top();//错误,s.top()只能返回引用
*/