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;
}
相关推荐
学逆向的1 天前
C 枚举变量
c语言·开发语言·网络安全
冷凝雨1 天前
前导零、后导零、最高有效位、最低有效位计算(C)
c语言
鸥梨菌Honevid1 天前
C 语言 restrict 关键字深度解析:从“独占访问”承诺到编译器激进优化
c语言
企业数字化笔记1 天前
视频人体姿态怎么做三维可视化?2D关键点、深度局限与技术选型
人工智能·算法·音视频
?abc!1 天前
(数组)581. 最短无序连续子数组
数据结构·算法·leetcode
小郎君6581 天前
MPTT树复选框的半选状态:一棵百万节点树从递归到计数器,再到区间覆盖
算法
酌沧1 天前
MemT让记忆成为模型内生能力
jvm·人工智能·算法
水饺编程1 天前
第2章:Linux 基础,切换用户
linux·c语言·汇编
hold?fish:palm1 天前
40 二叉树的直径
c++·leetcode
Shimeri1 天前
越卷越像:我用遗传算法做了个"内卷"实验
算法·three.js·数据可视化·遗传算法·进化算法