牛客KY11 二叉树遍历

2024-01-07 20:35:50

牛客KY11 二叉树遍历
数组形式:

#include<bits/stdc++.h>

using namespace std;

const int N = 1e8 + 10;

int len, t;
char tree[N];
string s;

void create(int pos){
	char c = s[t ++ ];
	if(c == '#') return ;
	tree[pos] = c;
	create(pos * 2);
	create(pos * 2 + 1);
}

void coid(int pos){
	if(tree[pos] == 0) return ;
	coid(pos * 2);
	cout<<tree[pos]<<' ';
	coid(pos * 2 + 1);
}

int main()
{
	while(cin>>s){
		t = 0;
		create(1);
		coid(1);
		cout<<endl;
	}
	return 0;
}

指针形式:

#include<bits/stdc++.h>

using namespace std;

struct Tree{
	char val;
	Tree *left, *right;
	Tree(char c):val(c), left(NULL), right(NULL){};
};

int t;
string s;

Tree* build(){
	char c = s[t ++ ];
	if(c == '#') return NULL;
	Tree *root = new Tree(c);
	root->left = build();
	root->right = build();
	return root;
}

void coid(Tree* t){
	if(!t) return;
	coid(t->left);
	cout<<t->val<<' ';
	coid(t->right);
}

int main()
{
	while(cin>>s){
		t = 0;
		Tree *root = build();
		coid(root);
		cout<<endl;
	}
	return 0;
}

文章来源:https://blog.csdn.net/qiaodxs/article/details/135438053
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。