代码随想录day14 递归遍历 迭代遍历 统一迭代

递归遍历

/**
 * 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 pre(struct TreeNode* root,int* re,int* returnSize)
{
    if(root == NULL)
    return;
    re[(*returnSize)++] = root->val;
    pre(root->left,re,returnSize);
    pre(root->right,re,returnSize);
}

int* preorderTraversal(struct TreeNode* root, int* returnSize){
    *returnSize = 0;
    int *re = malloc(sizeof(int)*101);
    pre(root,re,returnSize);

    return re;
}

递归写法总结:
1.确定递归函数要哪些参数
2.确定单层递归逻辑:如上所示前序遍历先根节点,再左最后右。
3.确定终止条件:指向NULL时开始返回。

二叉树的迭代遍历(用栈模拟递归)

栈中要存放的是节点二分节点中的变量保证能够更新节点
栈是后进先出所以先将右节点压进去才能保证弹出来的是先左后右

自己画一画

/**
 * 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_SIZE 100

// Defining the stack structure
typedef struct {
    struct TreeNode* items[MAX_SIZE];
    int top;
} Stack;

// Initializing the stack
void initialize(Stack *s) {
    s->top = -1;
}

// Check if the stack is full
int isFull(Stack *s) {
    return s->top == MAX_SIZE - 1;
}

// Check if the stack is empty
int isEmpty(Stack *s) {
    return s->top == -1;
}

// Add elements into stack
void push(Stack *s, struct TreeNode* value) {
    // Check if the stack is full
    if (isFull(s)) {
        printf("Stack is full\n");
    } else {
        s->top++;
        s->items[s->top] = value;
    }
}

// Remove element from stack
struct TreeNode* pop(Stack *s) {
    // Check if the stack is empty
    if (isEmpty(s)) {
        printf("Stack is empty\n");
        return NULL;
    } else {
        struct TreeNode* temp = s->items[s->top];
        s->top--;
        return temp;
    }
}


int* preorderTraversal(struct TreeNode* root, int* returnSize){
    Stack* s = (Stack*)malloc(sizeof(Stack));
    *returnSize = 0;
    int* ret = malloc(sizeof(int)*100);
    if(root == NULL) return ret;
    initialize(s);
    push(s,root);
    while(!isEmpty(s))
    {
        struct TreeNode* node = pop(s);
        ret[(*returnSize)++] = node->val;
        if(node->right) push(s,node->right);
        if(node->left) push(s,node->left);
        //root = node;没必要啊
    }

    return ret;
}

统一迭代先算了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值