您的位置:首页 > 其它

二叉树的建立与遍历

2016-07-25 21:15 411 查看
二叉树的建立与遍历:

#include <iostream>
#include<string>
#include <vector>
#include<algorithm>
#include <stack>
#include <queue>
using namespace std;
//二叉树的建立与遍历
typedef struct TreeNode
{
char val;
struct TreeNode* left;
struct TreeNode* right;

}TreeNode;
void CreateTree(TreeNode* &root)
{
char data;
cin>>data;
if(data=='#')
root=NULL;
else
{
root=new TreeNode;
root->val=data;
CreateTree(root->left);
CreateTree(root->right);
}

}
void PreTree(TreeNode* root)
{
if(root)
{
cout<<root->val<<" ";
PreTree(root->left);
PreTree(root->right);
}

}
void InTree(TreeNode* root)
{
if(root)
{
InTree(root->left);
cout<<root->val<<" ";
InTree(root->right);
}

}
void PostTree(TreeNode* root)
{
if(root)
{
PostTree(root->left);
PostTree(root->right);
cout<<root->val<<" ";
}

}
/* 先序遍历(非递归)
思路:访问T->data后,将T入栈,遍历左子树;遍历完左子树返回时,栈顶元素应为T,出栈,再先序遍历T的右子树。
*/
void PreTree2(TreeNode* root)
{
stack<TreeNode*>s;
while(!s.empty()||root)
{
if(root)
{
s.push(root);
cout<<root->val<<" ";
root=root->left;
}
else
{
root=s.top();
s.pop();
root=root->right;
}

}

}
/* 中序遍历(非递归)
思路:T是要遍历树的根指针,中序遍历要求在遍历完左子树后,访问根,再遍历右子树。
先将T入栈,遍历左子树;遍历完左子树返回时,栈顶元素应为T,出栈,访问T->data,再中序遍历T的右子树。
*/
void InTree2(TreeNode* root)
{
stack<TreeNode*>s;
while(!s.empty()||root)
{
if(root)
{
s.push(root);
root=root->left;

}
else
{
root=s.top();
cout<<root->val<<" ";
s.pop();
root=root->right;
}

}

}
void PostTree2(TreeNode* root)
{
stack<TreeNode*>s;
TreeNode* preroot=NULL;
while(!s.empty()||root)
{
while(root)//一直左走到底
{
s.push(root);
root=root->left;
}
root=s.top();
if(root->right==NULL||root==preroot) // 当前节点的右孩子如果为空或者已经被访问,则访问当前节点
{
cout<<root->val<<" ";
s.pop();
root=NULL;
}
else
{
preroot=root;
root=root->right;
}

}
}
//层次遍历
void LevelTree(TreeNode* root)
{
queue<TreeNode*> q;
if(root)
q.push(root);
while(!q.empty())
{
root=q.front();
cout<<root->val<<" ";
q.pop();
if(root->left) q.push(root->left);
if(root->right)q.push(root->right);
}
}
int main()
{

TreeNode* root;
CreateTree(root);
cout<<"先序遍历递归:"<<endl;
PreTree(root);
cout<<endl;
cout<<"中序遍历递归:"<<endl;
InTree(root);
cout<<endl;
cout<<"后序遍历递归:"<<endl;
PostTree(root);
cout<<endl;

cout<<"先序遍历非递归:"<<endl;
PreTree2(root);
cout<<endl;
cout<<"中序遍历非递归:"<<endl;
InTree2(root);
cout<<endl;
cout<<"后序遍历非递归:"<<endl;
PostTree2(root);
cout<<endl;
cout<<"层次遍历非递归:"<<endl;
LevelTree(root);
cout<<endl;

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: