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;
}
相关推荐
凌肖战6 分钟前
力扣上刷题之C语言实现(数组)
c语言·算法·leetcode
秋夫人33 分钟前
B+树(B+TREE)索引
数据结构·算法
Jhxbdks1 小时前
C语言中的一些小知识(二)
c语言·开发语言·笔记
代码雕刻家1 小时前
数据结构-3.1.栈的基本概念
c语言·开发语言·数据结构
梦想科研社1 小时前
【无人机设计与控制】四旋翼无人机俯仰姿态保持模糊PID控制(带说明报告)
开发语言·算法·数学建模·matlab·无人机
Milo_K1 小时前
今日 leetCode 15.三数之和
算法·leetcode
Darling_001 小时前
LeetCode_sql_day28(1767.寻找没有被执行的任务对)
sql·算法·leetcode
AlexMercer10121 小时前
【C++】二、数据类型 (同C)
c语言·开发语言·数据结构·c++·笔记·算法
Greyplayground1 小时前
【算法基础实验】图论-BellmanFord最短路径
算法·图论·最短路径
蓑 羽1 小时前
力扣438 找到字符串中所有字母异位词 Java版本
java·算法·leetcode