您的位置:首页 > 其它

二叉树的三种遍历方法

2014-12-25 14:53 405 查看
/******************定义二叉树**************************/
//链式存储
struct BinaryTreeNode
{
int mValue;
BinaryTreeNode* mLeft;
BinaryTreeNode* mRight;
};
//顺序存储
struct BinaryTreeNode
{
int data[MAX_SIZE];
int length;
}

/******************递归实现***************************/
//先序遍历
int PreOrderTreeWalk(BinaryTreeNode* pNode)
{
if(pNode == NULL)
return 0;
printf(pNode->mValue);
PreOrderTreeWalk(pNode->mLeft);
PreOrderTreeWalk(pNode->mRight);
return 1;
}

//中序遍历
int InOrderTreeWalk(BinaryTreeNode* pNode)
{
if(pNode == NULL)
return 0;
PreOrderTreeWalk(pNode->mLeft);
printf(pNode->mValue);
PreOrderTreeWalk(pNode->mRight);
return 1;
}

//后序遍历
int PostOrderTreeWalk(BinaryTreeNode* pNode)
{
if(pNode == NULL)
return 0;
PreOrderTreeWalk(pNode->mLeft);
PreOrderTreeWalk(pNode->mRight);
printf(pNode->mValue);
return 1;
}

/*****************非递归实现***********************/
//先序遍历
int PreOrderTreeWalk(BinaryTreeNode* pNode)
{
std::Stack<BinaryTreeNode*> stack;
if(pNode == NULL)
return 0;

while(!stack.empty()||pNode)
{
while(pNode)
{
//先访问
printf(pNode->mValue);
stack.push(pNode);
//遍历左节点
pNode = pNode->mLeft;
}
//弹出根节点
pNode = stack.top();
stack.pop();
//遍历右节点
pNode = pNode->mRight;
}
}

//中序遍历
int int InOrderTreeWalk(BinaryTreeNode* pNode)
{
std::Stack<BinaryTreeNode*> stack;
if(pNode == NULL)
return 0;

while(!stack.empty()||pNode)
{
while(pNode!=NULL)
{
stack.push(pNode);
pNode = pNode->mLeft;
}
pNode = stack.top();
stack.pop();
printf(pNode->mValue);
pNode = pNode->mRight;
}
}

//后序遍历,用一个标记标记右子树是否访问过
int PostOrderTreeWalk(BinaryTreeNode* pNode)
{
std::Stack<BinaryTreeNode*> stack;
boolean flag[MAX_SIZE];
if(pNode == NULL)
return 0;
stack.push(pNode);
flag[stack.size()-1] = false;
while(!stack.empty()||pNode)
{
pNode = stack.top();
//左子树入栈,初始化
while(pNode)
{
stack.push(pNode);
flag[stack.size()-1] = false;//标记此时该节点右子树并未被访问
pNode = pNode-> mLeft;
}
//访问到最左节点
pNode = stack.top();
//访问右子树
if(pNode->mRight&&!flag[stack.size()-1])
{
flag[stack.size()-1] = true;
pNode = pNode-> mRight;
}
else
{
pNode = stack.top();
stack.pop();
printf(pNode->mValue);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: