C语言 | Leetcode C语言题解之第144题二叉树的前序遍历

题目:

题解:

cpp 复制代码
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;
}
相关推荐
im_AMBER19 分钟前
Leetcode 101 对链表进行插入排序
数据结构·笔记·学习·算法·leetcode·排序算法
踩坑记录42 分钟前
leetcode hot100 560.和为 K 的子数组 medium 前缀和 + 哈希表
leetcode
码农小韩1 小时前
基于Linux的C++学习——循环
linux·c语言·开发语言·c++·算法
Q741_1471 小时前
海致星图招聘 数据库内核研发实习生 一轮笔试 总结复盘(2) 作答语言:C/C++ 哈夫曼编码 LRU
c语言·数据库·c++·算法·笔试·哈夫曼编码·哈夫曼树
你怎么知道我是队长1 小时前
C语言---位域
c语言·开发语言
独自破碎E2 小时前
【队列】按之字形顺序打印二叉树
leetcode
AlenTech2 小时前
206. 反转链表 - 力扣(LeetCode)
数据结构·leetcode·链表
踩坑记录2 小时前
leetcode hot100 438. 找到字符串中所有字母异位词 滑动窗口 medium
leetcode·职场和发展
YuTaoShao3 小时前
【LeetCode 每日一题】1458. 两个子序列的最大点积——(解法三)状态压缩
算法·leetcode·职场和发展
橘颂TA3 小时前
【剑斩OFFER】算法的暴力美学——leetCode 946 题:验证栈序列
c++·算法·leetcode·职场和发展·结构与算法