二叉树的建立与遍历

二叉树的建立与遍历:

#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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值