llllmz

导航

144. 二叉树的前序遍历c

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
void preorder(struct TreeNode* root,int* temp,int* i){
    if(!root) return ;
    temp[(*i)++]=root->val;
    preorder(root->left,temp,i);
    preorder(root->right,temp,i);
}


int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    int* temp=(int*)malloc(sizeof(int)*100);
    for(int i=0;i<100;i++) temp[i]=-1;
    int i=0;
    preorder(root,temp,&i);
    *returnSize=i;
    return temp;
}

结果:

posted on 2024-02-29 22:40  神奇的萝卜丝  阅读(16)  评论(0)    收藏  举报