"Leetcode" 94. In-order traversal of binary tree

Language: C language
Idea: This question is basically similar to the preorder traversal of the binary tree I did before, the only difference is that the order of the two is different, the order of the middle order traversal is left subtree -> root -> right subtree Tree, but the overall problem-solving method is the same, you can refer to the detailed idea of ​​my last problem, and the link is below.
"Leetcode" 144. Preorder traversal of binary tree

code show as below

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int TreeSize(struct TreeNode* root)//计算节点数量方便开辟空间
{
    if(root==NULL)
    {
        return 0;
    }
    return TreeSize(root->left)+TreeSize(root->right)+1;
}

int* _inorderTraversal(struct TreeNode* root ,int* array, int* pIndex)
{
    if(root==NULL)
    {
        return;
    }
    _inorderTraversal(root->left,array, pIndex);
    array[*pIndex] = root->val;
    ++(*pIndex);
    _inorderTraversal(root->right, array, pIndex);
}

/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* inorderTraversal(struct TreeNode* root, int* returnSize)
{
    *returnSize=TreeSize(root);
    int*array=(int*)malloc(*returnSize * sizeof(int));
    
    int index=0;
     _inorderTraversal(root,array,&index);
    return array;
}

Submission results beat 98.54% of users

Guess you like

Origin blog.csdn.net/NanlinW/article/details/97010748