数据结构小作业——二叉树表达式加括号

问题描述

试给出算法将二叉树表达式中序遍历输出并加上相应的括号

参考

思路

先举几个例子看一看,正确输出是
((a+(b*(c-d)))-(e/f))
不要写成
(((a)+((b)*(©-(d))))-((e)/(f)))
两种情况:

1.叶子节点。只打印节点的值即可
2.非叶子节点。那么一定要在最外层加(),然后里面依次是左子树,当前结点值,右子树。
打印顺序:1.( 2.左子树 3.当前结点的值 4.右子树 5.)

code

打印二叉树

void print(nodePtr a)
{
	if(a == NULL)
	{
		return;
	}
	else
	{
		if(a->left && a->right)//当a的左右节点都非空时 
		{
			cout<<"(";
			print(a->left);
			cout<<a->ch;
			print(a->right);
			cout<<")";	
		} 
		else//当a为叶子节点时 
		{
			cout<<a->ch;
		}
	}
}

#include<stdio.h>
#include<iostream>
using namespace std;
typedef struct node{
	char ch;
	struct node *left;
	struct node *right;
}node, *nodePtr;
nodePtr create();//创建一棵二叉树 
void destroy(nodePtr a);//删除二叉树 
void print(nodePtr a);//加括号 
int main()
{
	nodePtr a = create();//创建二叉树
	print(a);//加括号打印 
 	destroy(a);//删除二叉树
	return 0; 
} 
nodePtr create()
{
	char ch;
	nodePtr a;
	scanf("%c",&ch);
	if(ch == ' ')
	{
		return NULL;
	}
	else
	{
		a = new node;
		a->ch = ch;
		a->left = create();
		a->right = create();
		return a;
	}
}
void destroy(nodePtr a)
{
	if(a == NULL)
	{
		return;
	}
	else
	{
		destroy(a->left);
		destroy(a->right);
		delete a;
	}
}
void print(nodePtr a)
{
	if(a == NULL)
	{
		return;
	}
	else
	{
		if(a->left && a->right)//当a的左右节点都非空时 
		{
			cout<<"(";
			print(a->left);
			cout<<a->ch;
			print(a->right);
			cout<<")";	
		} 
		else//当a为叶子节点时 
		{
			cout<<a->ch;
		}
	}
}
发布了74 篇原创文章 · 获赞 4 · 访问量 1428

猜你喜欢

转载自blog.csdn.net/weixin_44814121/article/details/102790205