0
点赞
收藏
分享

微信扫一扫

【手把手带你刷好题】—— 33.二叉树的前序+中序+后序遍历(三道力扣)


目录

​​原题一:二叉树的前序遍历​​

​​原题二:二叉树的中序遍历​​

​​原题三:二叉树的后序遍历​​

​​结语​​

【前言】


今天是刷题打卡第33天!

加油啦。


【手把手带你刷好题】—— 33.二叉树的前序+中序+后序遍历(三道力扣)_c语言

原题一:二叉树的前序遍历

题目描述:

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

示例:

【手把手带你刷好题】—— 33.二叉树的前序+中序+后序遍历(三道力扣)_职场和发展_02 

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

 代码执行:

/**
* 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){
int* arr = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
PrevOrder(root, arr,returnSize);
return arr;
}

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

原题二:二叉树的中序遍历

题目描述:

给定一个二叉树的根节点 ​​root​​ ,返回它的 中序 遍历。

示例:

【手把手带你刷好题】—— 33.二叉树的前序+中序+后序遍历(三道力扣)_职场和发展_02

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

 代码执行:

/**
* 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* inorderTraversal(struct TreeNode* root, int* returnSize){
int* arr = (int*)malloc(sizeof(int)*100);
*returnSize = 0;
InOrder(root, arr,returnSize);
return arr;
}

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

原题三:二叉树的后序遍历

题目描述:

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]  
1
\
2
/
3

输出: [3,2,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().
*/
int* postorderTraversal(struct TreeNode* root, int* returnSize){
int* arr = (int*)malloc(sizeof(int)*100);
*returnSize = 0;
PostOrder(root, arr, returnSize);
return arr;
}

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

结语


今天是刷题打卡第33天!

加油吧少年。


【手把手带你刷好题】—— 33.二叉树的前序+中序+后序遍历(三道力扣)_算法_04



举报

相关推荐

力扣:二叉树的中序遍历

0 条评论