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;
}
相关推荐
Q741_1476 分钟前
C++ 栈 模拟 力扣 394. 字符串解码 每日一题 题解
c++·算法·leetcode·模拟·
AI科技星13 分钟前
张祥前统一场论:空间位移条数概念深度解析
数据结构·人工智能·经验分享·算法·计算机视觉
Wuliwuliii17 分钟前
闵可夫斯基和、需存储的最小状态集
c++·算法·动态规划·闵可夫斯基和
CoovallyAIHub25 分钟前
颠覆认知!遥感船舶检测“越深越好”是误区?LiM-YOLO证明“少即是多”
深度学习·算法·计算机视觉
byzh_rc29 分钟前
[算法设计与分析-从入门到入土] 贪心算法
算法·动态规划
Felven35 分钟前
C. Contrast Value
c语言·开发语言·算法
natide37 分钟前
表示/嵌入差异-1-欧几里得距离(Euclidean Distance)-L2 距离(L2 distance)-欧式距离的标准化
人工智能·pytorch·python·深度学习·算法·自然语言处理
雪花desu38 分钟前
【Hot100-Java简单】:两数之和 (Two Sum) —— 从暴力枚举到哈希表的思维跃迁
java·数据结构·算法·leetcode·哈希表
qzhqbb39 分钟前
群智能计算核心算法全解析
人工智能·算法
leaves falling40 分钟前
c语言打印闰年
java·c语言·算法