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;
}
相关推荐
LG.YDX11 小时前
笔试训练48天:mari和shiny(动态规划 - 线性dp)
数据结构·算法
m0_5648768411 小时前
提示词应用
深度学习·学习·算法
qq_2837200511 小时前
Transformer 高频面试题及答案
算法·面试·transformer
承渊政道11 小时前
【递归、搜索与回溯算法】(floodfill算法:从不会做矩阵题,到真正掌握搜索扩散思想)
数据结构·c++·算法·leetcode·矩阵·dfs·bfs
谭欣辰11 小时前
字典树:高效字符串处理利器
c++·算法
卢锡荣11 小时前
单芯双 C 盲插,一线通显电 ——LDR6020P 盲插 Type‑C 显示器方案深度解析
c语言·开发语言·ios·计算机外设·电脑
俺爱吃萝卜11 小时前
Java 性能调优实战:从 JVM 内存模型到垃圾回收算法优化
java·jvm·算法
legendary_16311 小时前
PD显示器方案新维度:Type-C充电,投屏,显示技术革新
c语言·开发语言·计算机外设
码农爱学习11 小时前
用简单的例子,来理解C指针
c语言·开发语言
鹿角片ljp12 小时前
LeetCode215: 数组中的第K个最大元素 —— 从快速选择到堆排
算法·排序算法