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

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

https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

#include<stdlib.h>
/**
 * struct TreeNode {
 *  int val;
 *  struct TreeNode *left;
 *  struct TreeNode *right;
 * };
 */
/**
#include<stdlib.h>
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 *
 * @param root TreeNode类 the root of binary tree
 * @return int整型二维数组
 * @return int* returnSize 返回数组行数
 * @return int** returnColumnSizes 返回数组列数
 */
void num(struct TreeNode* root, int* number) {
    if (root) {
        (*number)++;
        num(root->left, number);
        num(root->right, number);
    }
}

void xian(struct TreeNode* root, int* i, int* xi) {
    if (root) {
        xi[*i] = root->val;
        (*i)++;
        //printf("%d",root->val);
        xian(root->left, i, xi);
        xian(root->right, i, xi);
    }
}
void zhong(struct TreeNode* root, int* z, int* zh) {
    if (root) {
        zhong(root->left, z, zh);
        zh[*z] = root->val;
        (*z)++;
        //printf("%d",root->val);
        zhong(root->right, z, zh);
    }
}
void hou(struct TreeNode* root, int* h, int* ho) {
    if (root) {
        hou(root->left, h, ho);
        hou(root->right, h, ho);
        ho[*h] = root->val;
        (*h)++;
        //printf("%d",root->val);
    }
}
int** threeOrders(struct TreeNode* root, int* returnSize,
                  int** returnColumnSizes ) {
    // write code here
    *returnSize = 3;
    int number;
    num(root, &number);
    int** tree= (int**)malloc(*returnSize * sizeof(int*));
    int* xi = (int*)malloc(number * sizeof(int));
    int* zh = (int*)malloc(number * sizeof(int));
    int* ho = (int*)malloc(number * sizeof(int));
    *returnColumnSizes = (int*)malloc(*returnSize * sizeof(int));
    for (int i = 0; i < *returnSize; i++) {
        (*returnColumnSizes)[i] = number;
    }
    int x = 0;
    int z = 0;
    int h = 0;
    xian(root, &x, xi);
    zhong(root, &z, zh);
    hou(root, &h, ho);
    tree[0] = xi;
    tree[1] = zh;
    tree[2] = ho;
    return tree;

}

二叉树的遍历直接使用递归就行,这道题主要是卡在于二维数组的表示上

全部评论

相关推荐

叶扰云倾:进度更新,现在阿里云面完3面了,感觉3面答得还行,基本都答上了,自己熟悉的地方也说的比较细致,但感觉面试官有点心不在焉不知道是不是不想要我了,求阿里收留,我直接秒到岗当阿里孝子,学校那边的房子都退租了,下学期都不回学校,全职猛猛实习半年。这种条件还不诱人吗难道 然后现在约到了字节的一面和淘天的复活赛,外加猿辅导。华为笔试完没动静。 美团那边之前投了个base广州的,把我流程卡麻了,应该是不怎么招人,我直接简历挂了,现在进了一个正常的后端流程,还在筛选,不知道还有没有hc。
点赞 评论 收藏
分享
05-12 17:28
已编辑
门头沟学院 硬件开发
ldf李鑫:不说公司名祝你以后天天遇到这样的公司
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务