zoukankan      html  css  js  c++  java
  • 【leetcode】144. 二叉树的前序遍历

    void recursion(struct TreeNode* root,int* returnSize,int* arr){
        if (!root)
            return;    
        arr[(*returnSize)++]=root->val;
        recursion(root->left,returnSize,arr);
        recursion(root->right,returnSize,arr);
    }
    int* preorderTraversal(struct TreeNode* root, int* returnSize){
        int* arr=(int*)calloc(1000,sizeof(int));
        *returnSize=0;
        recursion(root,returnSize,arr);
        return arr;
    }
    int* preorderTraversal(struct TreeNode* root, int* returnSize) {
        int* res = malloc(sizeof(int) * 2000);
        *returnSize = 0;
        if (root == NULL) {
            return res;
        }
    
        struct TreeNode* stk[2000];
        struct TreeNode* node = root;
        int stk_top = 0;
        while (stk_top > 0 || node != NULL) {
            while (node != NULL) {
                res[(*returnSize)++] = node->val;
                stk[stk_top++] = node;
                node = node->left;
            }
            node = stk[--stk_top];
            node = node->right;
        }
        return res;
    }
    int* preorderTraversal(struct TreeNode* root, int* returnSize) {
        int* res = malloc(sizeof(int) * 2000);
        *returnSize = 0;
        if (root == NULL) {
            return res;
        }
    
        struct TreeNode *p1 = root, *p2 = NULL;
    
        while (p1 != NULL) {
            p2 = p1->left;
            if (p2 != NULL) {
                while (p2->right != NULL && p2->right != p1) {
                    p2 = p2->right;
                }
                if (p2->right == NULL) {
                    res[(*returnSize)++] = p1->val;
                    p2->right = p1;
                    p1 = p1->left;
                    continue;
                } else {
                    p2->right = NULL;
                }
            } else {
                res[(*returnSize)++] = p1->val;
            }
            p1 = p1->right;
        }
        return res;
    }
  • 相关阅读:
    Django搭建环境_初始化
    Python3 获取以及解析json格式
    python遍历目录树删除指定后缀的文件
    redis基础
    Centos7 更换阿里yum源
    Python3 实现带cookie登陆网站--自动
    Python3 requests实现cookie登陆--手动
    Flask中使用Editormd上传图片
    Flask中数据库的多对多关系
    Flask中博客类的Post实现
  • 原文地址:https://www.cnblogs.com/ganxiang/p/14173880.html
Copyright © 2011-2022 走看看