//树中节点的定义
typedef struct _BTNode
{
int data;
struct _BTNode *lchild;
struct _BTNode *rchild;
}BiTNode ,*BiNTree;
//树的层次遍历-- 先进先出 需要借助队列来实现
void BinaryTreeLevelOrder(BiNTree root)
{
queue<BiTNode*> q;
if(root==NULL)
return;
q.push(root);
while(!q.empty())
{
BiTNode *p = q.front();
cout<<p->data<<endl;
if(p->lchild!=NULL)
{
q.push(p->lchild);
}
if(p->rchild!=NULL)
{
q.push(p->rchild);
// TravelByLayer(T->rchild);
}
q.pop();
}
}
//二叉树的深度优先遍历--非递归形式 由于先进后出,因而要借助栈
void BinaryTreeDepthFirstOrder(BiNTree root)
{
stack<BiTNode*> s;
if(root==NULL)
return;
//q.push(T);
s.push(root);
while(!s.empty())
{
BiTNode *p = s.top();
cout<< p->data<<endl;
s.pop();
if(p->rchild!=NULL)
{
s.push(p->rchild);
}
if(p->lchild!=NULL)
{
s.push(p->lchild);
}
}
}
//二叉树的深度遍历--借助于递归实现
void TravelByDeptWithtRecursion(BiNTree root)
{
if(root==NULL)
return;
cout<<root->data<<endl;
TravelByDeptWithtRecursion(root->lchild);
TravelByDeptWithtRecursion(root->rchild);
}
//二叉树的前序遍历--采用递归形式实现
void PreOrderWithRecursion(BiNTree root)
{
if (root==NULL)
{
return ;
}
cout<<root->data<<endl;
PreOrderWithRecursion(root->lchild);
PreOrderWithRecursion(root->rchild);
}
//二叉树的前序遍历 --非递归形式实现
void PreOrderWithoutRecursion(BiNTree root)
{
if (root==NULL)
{
return ;
}
stack<BiTNode*> s;
s.push(root);
while(!s.empty())
{
cout<<s.top()->data<<endl;
BiTNode *p = s.top();
s.pop();
if (p->rchild!=NULL)
{
s.push(p->rchild);
}
if (p->lchild!=NULL)
{
s.push(p->lchild);
}
}
}
//二叉树的中序遍历--采用递归形式实现
void BinaryTreeInOderWithRecursion(BiNTree root)
{
if (root==NULL)
return;
BinaryTreeInOderWithRecursion(root->lchild);
cout<<root->data<<endl;
BinaryTreeInOderWithRecursion(root->rchild);
}
//中序遍历的非递归实现
void BinaryTreeInOderWithoutRecursion(BiNTree root)
{
if (root==NULL)
{
return ;
}
stack<BiTNode*> s;
//s.push(T);
BiTNode* p = root;
while(!s.empty()||p)
{
while(p!=NULL)
{
s.push(p);
p = p->lchild;
}//先走到最左分支
if (!s.empty())//之后出栈
{
p = s.top();
s.pop();
cout<<p->data<<endl;
p = p ->rchild;//遍历右子树 进行新的一轮左子树的遍历
}
}
}
//后序遍历的递归实现
void BinaryTreePostOrderWithRecursion(BiNTree root)
{
if (root==NULL)
return ;
BinaryTreePostOrderWithRecursion(root->lchild);
BinaryTreePostOrderWithRecursion(root->rchild);
cout<<root->data<<endl;
}
void BinaryTreePostOrderWithoutRecursion(BiNTree root)
{
if (root==NULL)
return ;
stack<BiTNode*> s;
BiTNode *pCur,*pLastVisit;//记录当前访问的节点和标记上次访问的节点
pCur =root;
pLastVisit ==NULL;
while(pCur!=NULL)
{
s.push(pCur);
pCur = pCur->lchild;
}
while(!s.empty())
{
//走到这里,说明已经遍历到了子树的最左边
pCur = s.top();
s.pop();
//一个根节点被访问的前提是:无右子树或者右子树已经被访问过了
if (pCur->rchild==NULL||pCur->rchild==pLastVisit)
{
cout<< pCur->data<<endl;
pLastVisit =pCur;
}
else
{
//根节点入栈
s.push(pCur);
//进入右子树,并且可以肯定右子树必定不为空
pCur = pCur->rchild;
while(pCur)
{
s.push(pCur);
pCur = pCur->lchild;
}
}
}
}