【leetcode】94. 二叉树的中序遍历

 

int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    *returnSize = 0;
    int* res = malloc(sizeof(int) * 501);
    struct TreeNode** stk = malloc(sizeof(struct TreeNode*) * 501);
    int top = 0;
    while (root != NULL || top > 0) {
        while (root != NULL) {
            stk[top++] = root;
            root = root->left;
        }
        root = stk[--top];
        res[(*returnSize)++] = root->val;
        root = root->right;
    }
    return res;
}

 

void recursion(struct TreeNode* root, int* returnSize,int* arr){
    if(!root) return;
    recursion(root->left,returnSize,arr);
    arr[(*returnSize)++]=root->val;
    recursion(root->right,returnSize,arr);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize){
    *returnSize=0;
    int* arr=(int*)calloc(1000,sizeof(int));
    recursion(root,returnSize,arr);
    return arr;
}

 

posted @ 2020-12-14 15:25  温暖了寂寞  阅读(91)  评论(0编辑  收藏  举报