0
点赞
收藏
分享

微信扫一扫

形态学笔记:侵蚀+膨胀+开运算+闭运算+形态学梯度+顶帽运算+黑帽运算

独西楼Q 03-01 09:00 阅读 4

94. Binary Tree Inorder Traversal

Given the root of a binary tree, return the inorder traversal of its nodes’ values.
 

Example 1:
Example 2:
Example 3:
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:
/**
 * 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;
}
举报

相关推荐

0 条评论