牛客KY11 二叉树遍历

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

#include

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

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

你可能感兴趣的:(算法,数据结构)