题海拾贝:二叉树遍历
Hello大家好!很高兴我们又见面啦!给生活添点passion,开始今天的编程之路!
我的博客:<但凡.
我的专栏:《编程之路》、《数据结构与算法之美》、《题海拾贝》
欢迎点赞,关注!
1、题目
2、题解
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include<stdlib.h>
struct node
{
char val;
struct node* left;
struct node* right;
};
struct node* buyNode(char val)
{
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->left = newnode->right = NULL;
newnode->val = val;
return newnode;
}
struct node* buildTree(char* arr,int* a)
{
if (arr[(*a)] == '#')
{
(*a)++;
return NULL;
}
struct node* newnode = buyNode(arr[(*a)]);
struct node* root = newnode;
(*a)++;
root->left=buildTree(arr, a);
root->right=buildTree(arr,a);
return root;
}
void Inorder(struct node* root)
{
if (root == NULL)
{
return;
}
Inorder(root->left);
printf("%c ", root->val);
Inorder(root->right);
}int main()
{
char arr[100];
int a = 0;
//存放数据
scanf("%s", arr);
//建树
struct node* root=buildTree(arr,&a);
Inorder(root);
return 0;
}