前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >中序遍历二叉树(栈思想)

中序遍历二叉树(栈思想)

作者头像
用户2965768
发布2018-12-18 17:16:39
5360
发布2018-12-18 17:16:39
举报
文章被收录于专栏:wymwym
代码语言:javascript
复制
void inorder(node *root)
{
	deque<node*> q;
	while(!q.empty())q.pop_front();
	node * t = root;
	do{
		while(t)
		{
			q.push_back(t);
			t = t->lc;
		}
		t = q.back();
		printf("%c ",t->ch);
		q.pop_back();
		if(t->rc)
		{
           t = t->rc; 	
		}else t = NULL;
		
	}while(t||(!q.empty()));
	
}

完整代码如下,这是我在做了广义表建立二叉树后顺便写的中序遍历二叉树,所以输入是广义表

例如:A(B(E(K,L),F),C(D(,H)))

代码语言:javascript
复制
#include <bits/stdc++.h>
using namespace std;
struct node{
	char ch;
	node *lc,*rc;
}; 
char s[100];
int flag=0;
int n;
int i=0;
node * build_tree()
{
	if(i>=n)
	return NULL;
	node *p = new node;
	p->lc = NULL; p->rc = NULL; p->ch = '0';//初始化 
  for(;i<n;i++)
	{
	if(flag)
	{
		flag = 0;
		p->rc = build_tree();
		
	}else if(s[i]=='(')
	{
		++i;
		p->lc = build_tree(); 
		
	}else if(s[i]==',')
	{	
	    flag = 1; 
	    if(p->ch=='0')return NULL;
	    else return p;
	}else if(s[i]>='A'&&s[i]<='Z')
	{
		p->ch = s[i];
	}else if(s[i]==')')
	{
		return p;
	}
	
	}
	return p;
}

void inorder(node *root)
{
	deque<node*> q;
	while(!q.empty())q.pop_front();
	node * t = root;
	do{
		while(t)
		{
			q.push_back(t);
			t = t->lc;
		}
		t = q.back();
		printf("%c ",t->ch);
		q.pop_back();
		if(t->rc)
		{
           t = t->rc; 	
		}else t = NULL;
		
	}while(t||(!q.empty()));
	
}

int main()
{
 	scanf("%s",s);
 	n = strlen(s);
 	node *root = build_tree();
	inorder(root);
	
	return 0;
}
//A(B(E(K,L),F),C(D(,H)))
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月26日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档