94-二叉树中序遍历-包含main的C程序

//题目:https://leetcode.cn/problems/binary-tree-inorder-traversal/

//方法一:递归
//思路与算法
//
//首先我们需要了解什么是二叉树的中序遍历:
// 按照访问左子树——根节点——右子树的方式遍历这棵树,
// 而在访问左子树或者右子树的时候我们按照同样的方式遍历,
// 直到遍历完整棵树。因此整个遍历过程天然具有递归的性质,
// 我们可以直接用递归函数来模拟这一过程。
//
//定义 inorder(root) 表示当前遍历到 root 节点的答案,那么按照定义,
// 我们只要递归调用 inorder(root.left) 来遍历 root 节点的左子树,
// 然后将 root 节点的值加入答案,再递归调用inorder(root.right)
// 来遍历 root 节点的右子树即可,递归终止的条件为碰到空节点。

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

typedef struct TreeNode {
    int val;
    struct TreeNode* left = NULL;
    struct TreeNode* right = NULL;
}TreeNode;

//反序列化:https://leetcode.cn/problems/serialize-and-deserialize-binary-tree/solution/c-bfs-ceng-xu-bian-li-by-hukp-kare/
TreeNode* deserialize(char* data)
{
#define N 20002     // less than 20002 would break some test case.
    if (!data) {
        return NULL;
    }

    struct TreeNode* root = (struct TreeNode*) malloc(sizeof(struct TreeNode) * N);
    struct TreeNode* node;

    struct TreeNode *queue[N]; //通过队列,完成不断更新root的作用
    int front = 0;
    int rear = 0;

    char* token = strtok(data, ",");
    root->val = atoi(token);
    queue[rear++] = root;
    while (token != NULL) {
        node = queue[front++];

        token = strtok(NULL, ","); //左子树
        if (!token) { //最后一次调用strtok,将会返回NULL,因此,这里用NULL作为while终止条件
            break;
        }
        if (token[0] != '#') {
            struct TreeNode *node_l = (struct TreeNode*)malloc(sizeof(struct TreeNode));
            node_l->val = atoi(token);
            node->left = node_l;
            queue[rear++] = node_l;
        } else {
            node->left = NULL;
        }

        token = strtok(NULL, ",");      // right tree
        if (token[0] != '#') {
            struct TreeNode *node_r = (struct TreeNode*)malloc(sizeof(struct TreeNode));
            node_r->val = atoi(token);
            node->right = node_r;
            queue[rear++] = node_r;
        } else {
            node->right = NULL;
        }
    }
    return root;
}

void Inorder(struct TreeNode *root, int *ans, int *returnSize)
{
    if (root != NULL) {
        Inorder(root->left, ans, returnSize);
        ans[(*returnSize)++] = root->val;
        Inorder(root->right, ans, returnSize);
    }
}

int *inorderTraversal(struct TreeNode *root, int *returnSize)
{
    int *ans = (int *) malloc(sizeof(int) * 105);
    *returnSize = 0;
    Inorder(root, ans, returnSize);
    return ans;
}

int main()
{
    system("chcp 65001");
    /* 用例输入的用一维数组表示的二叉树,输入用例记得在最后加四个# */
    char nodeVal[] = {"3,9,20,#,#,15,7,#,#,#,#"};
    int nodeNum = 5;
    struct TreeNode* node = (TreeNode*)(malloc(sizeof(TreeNode)));

    node = deserialize(nodeVal);
    int*  root = (int*) malloc(sizeof(int) * N);
    int a;
    root = inorderTraversal(node, &a);
    for (int i = 0; i < nodeNum; i++) {
        printf("%d ", root[i]);
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/zhangyuexiang123/article/details/125360608