目录
原题一:二叉树的前序遍历
原题二:二叉树的中序遍历
原题三:二叉树的后序遍历
结语
【前言】
今天是刷题打卡第33天!
加油啦。
原题一:二叉树的前序遍历
题目描述:
给你二叉树的根节点 root
,返回它节点值的 前序 遍历。
示例:
输入: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
,返回它的 中序 遍历。
示例:
输入: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天!
加油吧少年。