数据结构之二叉树——二叉树的遍历
文章目录
一、二叉树的结构体表示
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
}TreeNode;
二、二叉树的前序遍历
1.递归表示
preorderTraversal函数
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int *list=malloc(sizeof(int)*501);
*returnSize=0;
preOrder(root,list,returnSize);
return list;
}
preOrder函数
void preOrder(struct TreeNode* root,int* list,int* returnSize){
if (root!=NULL)
{
list[(*returnSize)++]=root->val;
preOrder(root->left,list,returnSize);
preOrder(root->right,list,returnSize);
}
}
2.非递归表示
int* preorderTraversal(struct TreeNode* root, int* returnSize){
//定义TreeNode栈,并为该栈分配存储空间
struct TreeNode **stack = malloc(sizeof(struct TreeNode*)*501);
int top=0;
//定义结果数组
int* list = malloc(sizeof(int)*501);
*returnSize=0;
while (root!=NULL||top>0){
if (root!=NULL){
list[(*returnSize)++]=root->val;
stack[top++]=root->right;
root=root->left;
}else{
root=stack[--top];
}
}
return list;
}
三、二叉树的中序遍历
1.递归表示
void InOrder(struct TreeNode* root,int* res,int* returnSize){
if (root!=NULL){
InOrder(root->left,res,returnSize);
res[(*returnSize)++]=root->val;
InOrder(root->right,res,returnSize);
}
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int* res = malloc(sizeof(int)*501);
*returnSize=0;
InOrder(root,res,returnSize);
return res;
}
2.非递归表示
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
//为遍历返回的数组分配存储空间
int* res = malloc(sizeof(int)*501);
*returnSize=0;
//初始化存储二叉树结点的栈,并为该栈分配存储空间
struct TreeNode **stack = malloc(sizeof(struct TreeNode*)*501);
int top=0;
while (root!=NULL||top>0)
{
if(root!=NULL){
stack[top++]=root;
root=root->left;
}else{
root=stack[--top];
res[(*returnSize)++]=root->val;
root=root->right;
}
}
return res;
}
四、二叉树的后序遍历
1.递归表示
void posOrder(struct TreeNode* root,int* list,int* returnSize){
if (root!=NULL)
{
posOrder(root->left,list,returnSize);
posOrder(root->right,list,returnSize);
list[(*returnSize)++]=root->val;
}
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
int* list=malloc(sizeof(int)*501);
*returnSize=0;
posOrder(root,list,returnSize);
return list;
}
2.非递归表示
int* postorderTraversal(struct TreeNode* root, int* returnSize){
//迭代遍历需要借助栈来辅助存储二叉树的结点
//初始化TreeNode栈,并进行分配存储空间
struct TreeNode **stack=malloc(sizeof(struct TreeNode*)*501);
int top=0;
int *list=malloc(sizeof(int)*501);
*returnSize=0;
struct TreeNode *pre=NULL;
while (root!=NULL||top>0){
while (root!=NULL){
stack[top++]=root;
root=root->left;
}
root=stack[--top];
if (root->right==NULL||root->right==pre){
list[(*returnSize)++]=root->val;
pre=root;
root=NULL;
}else{
stack[top++];
root=root->right;
}
}
return list;
}
```## 标题