144. 二叉树的前序遍历

给你二叉树的根节点 root ,返回它节点值的 前序 遍历。

示例 1:

输入:root = [1,null,2,3]
输出:[1,2,3]

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

示例 4:

输入:root = [1,2]
输出:[1,2]

示例 5:

输入:root = [1,null,2]
输出:[1,2]

提示:

  • 树中节点数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

进阶:递归算法很简单,你可以通过迭代算法完成吗?

代码:

/**
* 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 preorder(struct TreeNode* root, int* res, int* returnSize) {
if (root == NULL)
return;
res[(*returnSize)++] = root->val;
preorder(root->left, res, returnSize);
preorder(root->right, res, returnSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int* res = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
preorder(root, res, returnSize);
return res;
}
// 精简后的代码
/**
* 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 preorder(struct TreeNode* root, int* returnSize, int* res) {
if (root) {
res[(*returnSize)++] = root->val;
preorder(root->left, returnSize, res);
preorder(root->right, returnSize, res);
}
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize = 0;
int* res = (int*)malloc(sizeof(int) * 1000);
preorder(root, returnSize, res);
return res;
}
// 非递归,即循环/迭代
/**
* 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().
*/
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
struct TreeNode* p = root;
struct TreeNode* q = (struct TreeNode*)malloc(sizeof(struct TreeNode));
struct TreeNode* stack[100];
int top = 0;
*returnSize = 0;
int* res = (int*)malloc(sizeof(int) * 100);
while (p || top != 0) {
if (p) {
stack[top++] = p;
res[(*returnSize)++] = p->val; // 在此处访问根结点
p = p->left;
} else {
q = stack[--top];
p = q->right;
}
}
return res;
}
posted @   有空  阅读(9)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
点击右上角即可分享
微信分享提示