leetcode:144.二叉树的前序遍历

leetcode:144.二叉树的前序遍历_第1张图片

/**
 * 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().
 */
int TreeSize(struct TreeNode* root)
{
    return root==NULL ? 0 : TreeSize(root->left)+TreeSize(root->right)+1;
}
void preorder(struct TreeNode* root,int* a,int* pi)
{
    if(root==NULL)
        return;
    a[(*pi)++] = root->val;//解引用地址就是值。
    preorder(root->left,a,pi);
    preorder(root->right,a,pi);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize){
    *returnSize = TreeSize(root);
    int* a = (int*)malloc(*returnSize * sizeof(int));
    int i = 0;
    preorder(root,a,&i);  //此处传入i的地址,如此递归过程中只有一个i

    return a;
}

你可能感兴趣的:(数据结构,leetcode,linux,算法)