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 小时前
第3章 Windows运行机理-3.1 内核分析(1)
c语言
罗湖老棍子1 小时前
【例 2】选课(信息学奥赛一本通- P1576)
算法·树上背包·树型动态规划
每天要多喝水1 小时前
动态规划Day33:编辑距离
算法·动态规划
每天要多喝水1 小时前
动态规划Day34:回文
算法·动态规划
weixin_477271692 小时前
马王堆帛书《周易》系统性解读(《函谷门》原创)
算法·图搜索算法
AomanHao2 小时前
【ISP】基于暗通道先验改进的红外图像透雾
图像处理·人工智能·算法·计算机视觉·图像增强·红外图像
We་ct2 小时前
LeetCode 226. 翻转二叉树:两种解法(递归+迭代)详解
前端·算法·leetcode·链表·typescript
大熊背2 小时前
APEX系统中为什么 不用与EV0的差值计算曝光参数调整量
人工智能·算法·apex·自动曝光
REDcker2 小时前
HDR Vivid 技术介绍
数据库·算法·视频·sdr·屏幕·显示技术·dhr
ab1515172 小时前
2.18完成109、112、113
算法