LeetCode //C - 94. Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal

Given the root of a binary tree, return the inorder traversal of its nodes' values.

Example 1:

Input: root = [1,null,2,3]
Output: [1,3,2]

Example 2:

Input: root = []
Output:[]

Example 3:

Input: root = [1]
Output:[1]

Constraints:
  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

From: LeetCode

Link: 94. Binary Tree Inorder Traversal


Solution:

Ideas:

This code defines a binary tree node structure, a helper function to compute the size of the binary tree (which is used to allocate the correct amount of memory for the result array), and a recursive function inorder that performs the inorder traversal and fills the result array. Finally, the inorderTraversal function sets up the necessary variables and calls the helper functions to complete the traversal.

Code:
c 复制代码
/**
 * Helper function to compute the size of the binary tree.
 */
int computeSize(struct TreeNode* root) {
    if (root == NULL) return 0;
    return computeSize(root->left) + computeSize(root->right) + 1;
}

/**
 * Recursive function to perform inorder traversal.
 */
void inorder(struct TreeNode* root, int* res, int* index) {
    if (root == NULL) return;

    inorder(root->left, res, index);     // Visit left subtree
    res[(*index)++] = root->val;         // Visit node
    inorder(root->right, res, index);    // Visit right subtree
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    *returnSize = computeSize(root);
    int* res = (int*)malloc(*returnSize * sizeof(int));
    int index = 0;
    inorder(root, res, &index);
    return res;
}
相关推荐
问好眼9 分钟前
《算法竞赛进阶指南》0x05 排序-1.电影
c++·算法·排序·信息学奥赛
CoderCodingNo11 分钟前
【GESP】C++八级考试大纲知识点梳理 (6) 图论算法:最小生成树与最短路
c++·算法·图论
DeepModel15 分钟前
【特征选择】嵌入法(Embedded)
人工智能·python·深度学习·算法
今儿敲了吗41 分钟前
算法复盘——前缀和
笔记·学习·算法
ulias2121 小时前
智能指针简述
开发语言·c++·算法
阿昭L1 小时前
Windows通用的C/C++工程CMakeLists
c语言·c++·windows·makefile·cmake
寻寻觅觅☆1 小时前
东华OJ-基础题-58-素数表(C++)
开发语言·c++·算法
AI成长日志1 小时前
【强化学习专栏】深度拆解:多智能体强化学习核心理论与工程实践
算法
Flying pigs~~1 小时前
基于TF_IDF和Bagging的文本分类全过程
算法·随机森林·机器学习·nlp·文本分类
树獭叔叔1 小时前
FFN 激活函数深度解析:从 ReLU 到 SwiGLU 的演进之路
算法·aigc·openai