二叉树的前序遍历
思路:
- 求二叉树根结点个数
- 动态开辟数组
- 前序遍历插入数据
typedef struct TreeNode TreeNode;
int TreeSize(TreeNode* root)
{
if(root == NULL)
{
return 0;
}
return 1+TreeSize(root->left)+TreeSize(root->right);
}
void _preorderTraversal(TreeNode* root,int* arr,int* pi)
{
if(root==NULL)
{
return;
}
arr[(*pi)++]=root->val;
_preorderTraversal(root->left,arr,pi);
_preorderTraversal(root->right,arr,pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize=TreeSize(root);
int* arr=(int*)malloc(sizeof(int)*(*returnSize));
if(arr==NULL)
{
perror("malloc fail!");
exit(1);
}
int i=0;
_preorderTraversal(root,arr,&i);
return arr;
}
二叉树的中序遍历
typedef struct TreeNode TreeNode;
int TreeSize(TreeNode* root)
{
if(root == NULL)
{
return 0;
}
return 1+TreeSize(root->left)+TreeSize(root->right);
}
void _inorderTraversal(TreeNode* root,int* arr,int* pi)
{
if(root==NULL)
{
return;
}
_inorderTraversal(root->left,arr,pi);
arr[(*pi)++]=root->val;
_inorderTraversal(root->right,arr,pi);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize=TreeSize(root);
int* arr=(int*)malloc(sizeof(int)*(*returnSize));
if(arr==NULL)
{
perror("malloc fail!");
exit(1);
}
int i=0;
_inorderTraversal(root,arr,&i);
return arr;
}
二叉树的后序遍历
typedef struct TreeNode TreeNode;
int TreeSize(TreeNode* root)
{
if(root == NULL)
{
return 0;
}
return 1+TreeSize(root->left)+TreeSize(root->right);
}
void _postorderTraversal(TreeNode* root,int* arr,int* pi)
{
if(root==NULL)
{
return;
}
_postorderTraversal(root->left,arr,pi);
_postorderTraversal(root->right,arr,pi);
arr[(*pi)++]=root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize=TreeSize(root);
int* arr=(int*)malloc(sizeof(int)*(*returnSize));
if(arr==NULL)
{
perror("malloc fail!");
exit(1);
}
int i=0;
_postorderTraversal(root,arr,&i);
return arr;
}
二叉树的构建及遍历
思路:
- 创建数组,并将用户输入的字符串进行保存
- 前序遍历构造二叉树
- 中序遍历打印二叉树
#include <stdio.h>
#include<stdlib.h>
typedef struct TreeNode
{
char data;
struct TreeNode* left;
struct TreeNode* right;
}TN;
TN* buynode(char x)
{
TN* newnode=(TN*)malloc(sizeof(TN));
if(newnode == NULL)
{
perror("malloc fail!");
exit(1);
}
newnode->data=x;
newnode->left=newnode->right=NULL;
return newnode;
}
TN* creatTree(char* arr,int* pi)
{
if(arr[*pi] == '#')
{
(*pi)++;
return NULL;
}
TN* root=buynode(arr[(*pi)++]);
root->left=creatTree(arr,pi);
root->right=creatTree(arr,pi);
return root;
}
void InOrder(TN* root)
{
if(root == NULL)
{
return;
}
InOrder(root->left);
printf("%c ",root->data);
InOrder(root->right);
}
int main() {
char arr[100];
scanf("%s",arr);
int i=0;
TN* root=creatTree(arr, &i);
InOrder(root);
return 0;
}