遍历二叉树——清华

题目描述

在这里插入图片描述

知识点

二叉树的遍历

结果

在这里插入图片描述
可以

实现

码前思考

  1. 由于“#”号的存在,我们可以直接进行模拟先序遍历来建造树。

代码实现

//我的想法是使用前序遍历来进行
#include "bits/stdc++.h"
using namespace std;

const int maxn = 110;

struct node{
	char data;
	node* lchild;
	node* rchild;
}; 

char input[maxn];
//记录当前的处理的是哪一个字符 
int loc;

node* newNode(char x){
	node* Node = new node;
	
	Node->data = x;
	Node->lchild = NULL;
	Node->rchild = NULL;
	
	return Node;
}

//这个函数用于返回当前读入先序遍历字符的根结点 
node* create(){
	//代表为空树 
	if(input[loc] == '#'){
		loc++;
		return NULL;
	} 
	
	node* root = new node;
	root->data = input[loc];
	loc++;
	root->lchild = create(); 
	root->rchild = create();
	
	return root;
}

void inOrder(node* root){
	if(root == NULL){
		return;
	}
	
	inOrder(root->lchild);
	printf("%c ",root->data);
	inOrder(root->rchild);
}

int main(){
	while(~(scanf("%s",input))){
		loc = 0;
		node* root = NULL;
		root = create();	
		
		//进行中序遍历
		inOrder(root);
		printf("\n"); 
	}
	return 0;
} 

码后思考

  1. 可以直接使用构造函数的,不用写一个专门的函数,哈哈,学习到了。如下:
//我的想法是使用前序遍历来进行
#include "bits/stdc++.h"
using namespace std;

const int maxn = 110;

struct node{
	char data;
	node* lchild;
	node* rchild;
	node(char _data):data(_data),lchild(NULL),rchild(NULL){} //构造函数在这里啦
}; 

char input[maxn];
//记录当前的处理的是哪一个字符 
int loc;

//node* newNode(char x){
//	node* Node = new node;
//	
//	Node->data = x;
//	Node->lchild = NULL;
//	Node->rchild = NULL;
//	
//	return Node;
//}

//这个函数用于返回当前读入先序遍历字符的根结点 
node* create(){
	//代表为空树 
	if(input[loc] == '#'){
		loc++;
		return NULL;
	} 
	
	node* root = new node(input[loc]);//使用构造函数
//	root->data = input[loc];
	loc++;
	root->lchild = create(); 
	root->rchild = create();
	
	return root;
}

void inOrder(node* root){
	if(root == NULL){
		return;
	}
	
	inOrder(root->lchild);
	printf("%c ",root->data);
	inOrder(root->rchild);
}

int main(){
	while(~(scanf("%s",input))){
		loc = 0;
		node* root = NULL;
		root = create();	
		
		//进行中序遍历
		inOrder(root);
		printf("\n"); 
	}
	return 0;
} 
发布了138 篇原创文章 · 获赞 3 · 访问量 3803

猜你喜欢

转载自blog.csdn.net/yc_cy1999/article/details/105259024
今日推荐