"Leetcode" 144. Preorder traversal of binary tree

Language: C language
Idea: The order of pre-order traversal is root -> left subtree -> right subtree (NLR). First, you need to calculate how much space needs to be opened up, but the size of the space cannot be opened up casually. Create a TreeSize() function calculation The number of nodes in the tree, how many nodes open up how much space, and then create a function _preorderTraversal(), use the order of preorder traversal to put each node into an array in turn, and finally output the array as the answer to the question.
The mind map is shown in the figure below. The
Insert picture description here_preorderTraversal() function is explained in detail in the
following figure. The initial value of index is 0, which points to the first element of the array. Put A into the array in the order of preorder traversal, and then index backward. Move and put B into the array, and so on, and finally put the entire tree into the array.
Insert picture description here
code show as below

int TreeSize(struct TreeNode* root)
{
      if(root==NULL)
    {
        return 0;
    }
    return TreeSize(root->left)+TreeSize(root->right)+1;
}

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

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

Submission results beat 99.14% of users

Guess you like

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