LeeCode刷题 二叉树 C语言

LeeCode官网
LeeCode二叉树
刚开始刷题没多久,我会陆续补充

二叉树的遍历

前序遍历

题目
LeeCode刷题 二叉树 C语言_第1张图片
代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
#define MAX 1024

void preorder(struct TreeNode* root, int *arr, int* index){
     
    if(!root) return;
    arr[(*index)++] = root->val;
    preorder(root->left, arr, index);
    preorder(root->right, arr, index);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
     
    *returnSize = 0;
    int *arr = (int*)malloc(MAX * sizeof(int));
    if(root!=NULL){
     
    	preorder(root, arr, returnSize);
	}
    return arr;
}

结果
LeeCode刷题 二叉树 C语言_第2张图片

中序遍历

题目
LeeCode刷题 二叉树 C语言_第3张图片
代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
#define MAXSIZE 1024

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
void inorder(struct TreeNode* root, int* ret, int* index ){
     
    if(root != NULL){
     
        inorder(root->left, ret, index);
        ret[(*index)++] = root->val;
        inorder(root->right, ret, index);
    }
}  
    
int* inorderTraversal(struct TreeNode* root, int* returnSize){
     
    int *ret = (int*)malloc(sizeof(int)*MAXSIZE);//分配存储空间
    *returnSize = 0;
    if(root != NULL){
     
       inorder(root, ret, returnSize);
    } 
    return ret;
}

结果:
在这里插入图片描述

后序遍历

题目
LeeCode刷题 二叉树 C语言_第4张图片
代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
#define MAXSIZE 1024

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
void postorder(struct TreeNode* root, int *ret, int *index){
     
    if(root!=NULL){
     
        postorder(root->left, ret, index);
        postorder(root->right, ret, index);
        ret[(*index)++] = root->val;
    }
}
int* postorderTraversal(struct TreeNode* root, int* returnSize){
     
    int *ret = (int*)malloc(sizeof(int)*MAXSIZE);
    *returnSize = 0;
    if(root != NULL){
     
        postorder(root, ret, returnSize);
    }
    return ret;
}

结果:
LeeCode刷题 二叉树 C语言_第5张图片

层序遍历

你可能感兴趣的:(数据结构,二叉树,leetcode)