//前序遍历的算法程序
void PreOrder(BiTNode *root)
{
if(root==NULL)
return ;
printf("%c ", root->data); //输出数据
PreOrder(root->lchild); //递归调用,前序遍历左子树
PreOrder(root->rchild); //递归调用,前序遍历右子树
}
//中序遍历的算法程序
void InOrder(BiTNode *root)
{
if(root==NULL)
return ;
InOrder(root->lchild); //递归调用,前序遍历左子树
printf("%c ", root->data); //输出数据
InOrder(root->rchild); //递归调用,前序遍历右子树
}
//后序遍历的算法程序
void PostOrder(BiTNode *root)
{
if(root==NULL)
return ;
PostOrder(root->lchild); //递归调用,前序遍历左子树
PostOrder(root->rchild); //递归调用,前序遍历右子树
printf("%c ", root->data); //输出数据
}
/*
二叉树的非递归前序遍历,前序遍历思想:先让根进栈,只要栈不为空,就可以做弹出操作,
每次弹出一个结点,记得把它的左右结点都进栈,记得右子树先进栈,这样可以保证右子树在栈中总处于左子树的下面。
*/
//recommend
void PreOrder_Nonrecursive(BiTree T) //先序遍历的非递归
{
if(!T)
return ;
stack<BiTree> s;
s.push(T);
while(!s.empty())
{
BiTree temp = s.top();
cout<<temp->data<<" ";
s.pop();
if(temp->rchild)
s.push(temp->rchild);
if(temp->lchild)
s.push(temp->lchild);
}
}
//recommend
void InOrderTraverse(BiTree T) // 中序遍历的非递归
{
if(!T)
return ;
stack<BiTree> s;
BiTree curr = T; // 指向当前要检查的节点
while(curr != NULL || !s.empty())
{
while(curr != NULL) // 一直向左走
{
s.push(curr);
curr = curr->lchild;
}
curr = s.top();
s.pop();
cout<<curr->data<<" ";
curr = curr->rchild;
}
}
//recommend
void PostOrder_Nonrecursive1(BiTree T) // 后序遍历的非递归
{
stack<BiTree> S;
BiTree curr = T ; // 指向当前要检查的节点
BiTree previsited = NULL; // 指向前一个被访问的节点
while(curr != NULL || !S.empty()) // 栈空时结束
{
while(curr != NULL) // 一直向左走直到为空
{
S.push(curr);
curr = curr->lchild;
}
curr = S.top();
// 当前节点的右孩子如果为空或者已经被访问,则访问当前节点
if(curr->rchild == NULL || curr->rchild == previsited)
{
cout<<curr->data<<" ";
previsited = curr;
S.pop();
curr = NULL;
}
else
curr = curr->rchild; // 否则访问右孩子
}
}
void LeverTraverse(BiTree T) //方法一、非递归层次遍历二叉树
{
queue <BiTree> Q;
BiTree p;
p = T;
if(p)
Q.push(p);
while(!Q.empty())
{
p = Q.front();
Q.pop();
printf("%c ",T->data);
if(p->lchild)
Q.push(p->lchild);
if(p->rchild)
Q.push(p->rchild);
}
}
int depth(BiTNode *T) //树的深度
{
if(!T)
return 0;
int d1,d2;
d1=depth(T->lchild);
d2=depth(T->rchild);
return (d1>d2?d1:d2)+1;
//return (depth(T->lchild)>depth(T->rchild)?depth(T->lchild):depth(T->rchild))+1;
}
int CountNode(BiTNode *T)
{
if(T == NULL)
return 0;
return 1+CountNode(T->lchild)+CountNode(T->rchild);
}
void PreOrder_Nonrecursive1(BiTree T) //先序遍历的非递归
{
if(!T)
return ;
stack<BiTree> s;
BiTree curr = T;
while(curr != NULL || !s.empty())
{
while(curr != NULL)
{
cout<<curr->data<<" ";
s.push(curr);
curr = curr->lchild;
}
if(!s.empty())
{
curr = s.top();
s.pop();
curr = curr->rchild;
}
}
}
void InOrderTraverse1(BiTree T) // 中序遍历的非递归
{
if(!T)
return ;
BiTree curr = T; // 指向当前要检查的节点
stack<BiTree> s;
while(curr != NULL || !s.empty())
{
while(curr != NULL)
{
s.push(curr);
curr = curr->lchild;
}//while
if(!s.empty())
{
curr = s.top();
s.pop();
cout<<curr->data<<" ";
curr = curr->rchild;
}
}
}
//转载请标明出处,原文地址:http://blog.csdn.net/hackbuteer1/article/details/6583988