Leetcode 144. 二叉树的前序遍历(DAY 9)迭代 递归 Morris

原题题目

Leetcode 144. 二叉树的前序遍历(DAY 9)迭代 递归 Morris_第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().
 */

#define MAX 1001

void visit(struct TreeNode* root,int* returnSize,int* arr)
{
     
    if(root)
    {
     
        arr[(*returnSize)++] = root->val;
        visit(root->left,returnSize,arr);
        visit(root->right,returnSize,arr);
    }
}

int* preorderTraversal(struct TreeNode* root, int* returnSize){
     
    int* arr = (int*)malloc(sizeof(int) * MAX);
    (*returnSize) = 0;
    visit(root,returnSize,arr);
    return arr;
}


代码实现(神级Morris)

/**
 * 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().
 */

#define MAX 1001

int* preorderTraversal(struct TreeNode* root, int* returnSize){
     
    int* arr = (int*)malloc(sizeof(int) * MAX);
    (*returnSize) = 0;
    struct TreeNode* position = NULL;
    while(root)
    {
     
        position = root->left;
        if(!position)
        {
     
            arr[(*returnSize)++] = root->val;
            root = root->right;
        }
        else
        {
     
            while(position->right != root && position->right)
                position = position->right;
            if(!position->right)
            {
     
                position->right = root;
                arr[(*returnSize)++] = root->val;
                root = root->left;
            }
            else
            {
     
                position->right = NULL;
                root = root->right;
            }
        }
    }
    return arr;
}


代码实现(非递归 迭代)

/**
 * 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().
 */

#define MAX 1001

int* preorderTraversal(struct TreeNode* root, int* returnSize){
     
    int* arr = (int*)malloc(sizeof(int) * MAX);
    (*returnSize) = 0;
    struct TreeNode* position = root;
    struct TreeNode* stack[MAX];
    int size = 0;
    while(position != NULL || size > 0)
    {
     
        while(position != NULL)
        {
     
            arr[(*returnSize)++] = position->val;
            stack[size++] = position;
            position = position->left;
        }
        position = stack[--size];
        position = position->right;
    }
    return arr;
}

你可能感兴趣的:(#,从c开始的进步之路,c语言)