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;
}
相关推荐
wanzhong23333 小时前
CUDA学习5-矩阵乘法(共享内存版)
深度学习·学习·算法·cuda·高性能计算
fufu03113 小时前
Linux环境下的C语言编程(四十八)
数据结构·算法·排序算法
Yingye Zhu(HPXXZYY)4 小时前
Solution to Luogu P6340
算法
小熳芋4 小时前
单词搜索- python-dfs&剪枝
算法·深度优先·剪枝
Xの哲學4 小时前
Linux SLAB分配器深度解剖
linux·服务器·网络·算法·边缘计算
bu_shuo4 小时前
MATLAB中的转置操作及其必要性
开发语言·算法·matlab
高洁015 小时前
图神经网络初探(2)
人工智能·深度学习·算法·机器学习·transformer
爱装代码的小瓶子5 小时前
算法【c++】二叉树搜索树转换成排序双向链表
c++·算法·链表
思成Codes5 小时前
数据结构:基础线段树——线段树系列(提供模板)
数据结构·算法
JAY_LIN——86 小时前
C语言>字符 (strlen) | 字符串函数(strcpy、strcat)
c语言