首页 > 试题广场 >

实现二叉树先序,中序和后序遍历

[编程题]实现二叉树先序,中序和后序遍历
  • 热度指数:170824 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一棵二叉树,分别按照二叉树先序,中序和后序打印所有的节点。

数据范围:,树上每个节点的val值满足 
要求:空间复杂度 ,时间复杂度
样例解释:
如图二叉树结构
示例1

输入

{1,2,3}

输出

[[1,2,3],[2,1,3],[2,3,1]]

说明

如题面图  
示例2

输入

{}

输出

[[],[],[]]

备注:

说明:本题目包含复杂数据结构TreeNode,点此查看相关信息
我这里是分开实现先序遍历、后序遍历、中序遍历
#include<stdio.h>
#include <stdlib.h>

struct node {
    char data;
    struct node* lchild, *rchild;
};
void tree_int(struct node** node) {
    *node = malloc(sizeof(struct node));
    (*node)->data = 0;
    (*node)->lchild = NULL;
    (*node)->rchild = NULL;
}
void create(char data, struct node** node) {
    struct node* temp_node = *node;
    while (temp_node) {
        if (!temp_node->data) {
            temp_node->data = data;
            break;
        } 
        else if (data <= temp_node->data) {
            if (!temp_node->lchild) {
                tree_int(&(temp_node->lchild));
                temp_node->lchild->data = data;
                break;
            } 
            else {
                temp_node = temp_node->lchild;
                continue;
            }
        } 
        else if (data > temp_node->data) {
            if (!temp_node->rchild) {
                tree_int(&(temp_node->rchild));
                temp_node->rchild->data = data; // 修正了这里
                break;
            } else {
                temp_node = temp_node->rchild;
                continue;
            }
        }
    }
}

void pre_order_tra(struct node* node) {
    if (!node) {
        // printf("NULL ");
        return ;
    }
    printf("%c ", node->data);
    pre_order_tra(node->lchild);
    pre_order_tra(node->rchild);
}
//后序遍历
void post_order_treaverse(struct node* node) {
    if (!node) {
        return;
    }
    post_order_treaverse(node->lchild);
    post_order_treaverse(node->rchild);
    printf("%c", node->data);

}
//中序遍历
void in_order_traverse(struct node* node) {
    //递归的终止条件
    if (!node) {
        // printf("NULL ");
        return ;
    }
    in_order_traverse(node->lchild);
    printf("%c", node->data);
    in_order_traverse(node->rchild);
}

//二叉树叶子节点的统计
int lef_num(struct node* node, int* count) {
    if (!node) {
        return 1;
    } else {
        //访问根节点,判断该结点是否为叶子节点
        if (!node->lchild && !node->rchild) {
            (*count)++;
        }
        //先序遍历左子树
        if (lef_num(node->lchild, count)) {
            //先序遍历右子树
            if (lef_num(node->rchild, count)) {
                return 1;
            }

        }

    }
    return *count;


}

int main() {
    struct node* root = NULL;
    char data[8] = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'};
    tree_int(&root);
    for (int i = 0; i < 8; i++) {
        create(data[i], &root);
    }
    // printf("先序遍历二叉树: ");
    // pre_order_tra(root);
    int  count = 0;
    post_order_treaverse(root);
    printf("\n");
    printf("%d", lef_num(root, &count));

}


发表于 2024-04-13 13:34:40 回复(0)
这搞啥,不是要一个二维数组吗??出了threeOrders就报段错误!!在本地复现,Windows和Linux环境下都没找到问题。快吐了。。。
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

typedef struct {
    int *r;
    int length;
    int capacity;
}tresult;

void tresult_init(tresult *t) {
    t->r = (int *) malloc(sizeof(int) * 2);
    t->capacity = 2;
    t->length = 0;
}

void tresult_add(tresult *t, int e) {
    if (t->length >= t->capacity) {
        int *p = (int *) realloc(t->r, t->capacity * 2 * sizeof(int));
        t->r = p;
        t->capacity *= 2;
    }
    t->r[t->length++] = e;
}

void preorder(struct TreeNode *node, tresult *re) {
    if (!node) {
        return;
    }
    tresult_add(re, node->val);
    preorder(node->left, re);
    preorder(node->right, re);
}

void midorder(struct TreeNode *node, tresult *re) {
    if (!node) {
        return;
    }
    midorder(node->left, re);
    tresult_add(re, node->val);
    midorder(node->right, re);
}

void postorder(struct TreeNode *node, tresult *re) {
    if (!node) {
        return;
    }
    postorder(node->left, re);
    postorder(node->right, re);
    tresult_add(re, node->val);
}

/**
 * 
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
 * @return int* returnSize 返回数组行数
 * @return int** returnColumnSizes 返回数组列数
 */
int** threeOrders(struct TreeNode* root, int* returnSize, int** returnColumnSizes ) {
    *returnSize = 3;
    int **r = (int **) malloc(sizeof(int *) * (*returnSize)); // row
    returnColumnSizes = (int **) malloc(sizeof(int *) * (*returnSize));
    tresult *trs = (tresult *) malloc(sizeof(tresult) * (*returnSize));
    for (int i = 0; i < *returnSize; i++) {
        tresult_init(trs + i);
        returnColumnSizes[i] = (int *) malloc(sizeof(int));
        *(returnColumnSizes[i]) = 0;
    }
    preorder(root, &trs[0]);
    midorder(root, &trs[1]);
    postorder(root, &trs[2]);
    for (int i = 0; i < *returnSize; i++) {
        *(returnColumnSizes[i]) = (trs + i)->length;
        // ??????
        r[i] = (int *) malloc((trs + i)->capacity * sizeof(int));
        memcpy(r[i], (trs + i)->r, (trs + i)->capacity * sizeof(int));
        // ??????
    }
    for (int i = 0; i < *returnSize; i++) {
        for (int j = 0; j < *(returnColumnSizes[i]); j++) {
            printf("%d ", r[i][j]);
        }
    }
    return r;
}


发表于 2022-11-07 14:54:27 回复(0)
static int gTotal = 0;
static int bufLen = 100;
void traversalPre(struct TreeNode* node, int* count, int** buf)
{
    if (!node) return;
    (*buf)[*count] = node->val;
    (*count)++;
    if (*count > bufLen) {
        bufLen += 1000;
        *buf = (int*)realloc(*buf, bufLen * 4);
    }

    printf("%d ", node->val);
    traversalPre(node->left, count, buf);
    traversalPre(node->right, count, buf);
}

void traversalMid(struct TreeNode* node, int* count, int* buf)
{
    if (!node) return;

    traversalMid(node->left, count, buf);
    buf[*count] = node->val;
    (*count)++;
    printf("%d ", node->val);
    traversalMid(node->right, count, buf);
}

void traversalNext(struct TreeNode* node, int* count, int* buf)
{
    if (!node) return;

    traversalNext(node->left, count, buf);
    traversalNext(node->right, count, buf);
    buf[*count] = node->val;
    (*count)++;
    printf("%d ", node->val);
}

/**
 *
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
 * @return int* returnSize 返回数组行数
 * @return int** returnColumnSizes 返回数组列数
 */
int** threeOrders(struct TreeNode* root, int* returnSize, int** returnColumnSizes) {
    static int* ret[3];
    //int** ret =  (int**) malloc(3*sizeof(int*));
    static int rs = 3;
    static int rcs[3] = { 0 };

    int* pre = (int*)malloc(bufLen * 4);
    int* mid = NULL;
    int* next = NULL;
    int retCount = 0;
    int count = 0;
    traversalPre(root, &count, &pre);
    retCount = count;
    printf(" retCount = %d\n", retCount);

    mid = (int*)malloc(count * 4);
    next = (int*)malloc(count * 4);
    count = 0;
    traversalMid(root, &count, mid);

    printf(" count = %d\n", count);
    count = 0;
    traversalNext(root, &count, next);
    printf(" count = %d\n", count);

    ret[0] = pre;
    ret[1] = mid;
    ret[2] = next;

    *returnSize = 3;
#if 10
    //#if 0
    rcs[0] = retCount;
    rcs[1] = retCount;
    rcs[2] = retCount;

    *returnColumnSizes = rcs;

#endif
    printf("count %d \n", count);


    return &ret;// write code here
}

发表于 2021-12-12 14:08:36 回复(0)
用c写的,哪位大佬帮忙看一下为啥返回的时候不对,res里的值也是对的,直接return res显示输出为空

int count(struct TreeNode* root){
    if(!root)
    {
        return 0;
    }
    return count(root->left)+count(root->right)+1;
}

void preOrder(struct TreeNode* root,int*res){
    if(root)
    {
        int countLeft = count(root->left); 
        res[0]=root->val;
        preOrder(root->left,res+1);
        preOrder(root->right,res+countLeft+1);        
    }
}

void midOrder(struct TreeNode* root,int*res){
    if(root)
    {
        int countLeft = count(root->left);
        res[countLeft]=root->val;
        midOrder(root->left,res);
        midOrder(root->right,res+countLeft+1);
    }

}

void postOrder(struct TreeNode* root,int*res){
    if(root)
    {
        int all = count(root);
        int countLeft = count(root->left);
        res[all-1]=root->val;
        postOrder(root->left,res);
        postOrder(root->right,res+countLeft);        
    }
}

int** threeOrders(struct TreeNode* root, int* returnSize, int** returnColumnSizes ) {
    // write code here
    int i = count(root);
    int **res=(int**) malloc(3*sizeof(int*));
    for(int j=0;j<3;j++)
    {
        res[j]= (int*) malloc(i*sizeof(int));
    }
    preOrder(root,res[0]);
    midOrder(root,res[1]);
    postOrder(root,res[2]);
    return res;
}
发表于 2021-08-23 23:04:13 回复(2)

问题信息

难度:
4条回答 15357浏览

热门推荐

通过挑战的用户

查看代码