练习4 - 二叉树输出

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<sstream>
using namespace std;
#define L 101
typedef struct node;
typedef node *tree;	//tree => &node;tree本身就代表地址了 
struct node{
	char data;
	tree left=NULL,right=NULL;	//默认设为NULL => 方便到底停止 
	int len=1;
};
tree root;
string s1="ABCDEFG";
string s2="CBDAFEG";
int build(int l1,int h1,int l2,int h2,tree root){	//递归目的 => 返回当前len 
	//递归 => 顺序建树 + 逆序设值
	int m = s2.find(s1[l1]);
	root->data = s1[l1];	//data赶快设置 => m为全局会修改 
	int llen=0,rlen=0;
	//存在左子树 
	bool flag = false;
	if(m>l2){
		flag = true;
		tree bt = new node;	//将bt变为局部变量 + new堆 = 不干扰 + 不销毁 
		root->left = bt;
		llen = build(l1+1,l1+m-l2,l2,m-1,bt);
	}
	if(m<h2){
		flag = true;
		tree bt2 = new node;	//将bt变为局部变量 + new堆 = 不干扰 + 不销毁 
		root->right = bt2;
		rlen = build(l1+m-l2+1,h1,m+1,h2,bt2);
	}
	root->len = llen + rlen;
	if(!flag) root->len++;	//叶节点为1 
	return root->len;
}
void view(tree bt){
	if(bt){
		for(int i=1;i<=bt->len;i++){
			cout << bt->data;
		}
		cout << endl;
		view(bt->left);
		view(bt->right);
	}
	
}
int main()
{
	//1.建树 
	root = new node;
	build(0,s1.length()-1,0,s2.length()-1,root);
	//2.遍历 
	view(root);
	return 0;
}
//cout << "输入:"

结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值