@ 代码随想录算法训练营第三周(C语言)|Day14(二叉树)
Day14、二叉树(包含题目 144.二叉树的前序遍历 145.二叉树的后序遍历 94.二叉树的中序遍历 )
144.二叉树的前序遍历 145.二叉树的后序遍历 94.二叉树的中序遍历
题目描述
如题
题目解答
//前
void preorder(struct TreeNode*root ,int * res,int*resSize){
if(root==NULL){
return;
}
res[(*resSize)++]=root->val;
preorder(root->left,res,resSize);
preorder(root->right,res,resSize);
}
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
int* res=(int*)malloc(sizeof(int)*100);
*returnSize=0;
preorder(root,res,returnSize);
return res;
}
//中
void postorder(struct TreeNode*root,int *res,int*returnSize){
if(root==NULL){
return;
}
postorder(root->left,res,returnSize);
postorder(root->right,res,returnSize);
res[(*returnSize)++]=root->val;
}
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
int*res=(int*)malloc(sizeof(int)*100);
*returnSize=0;
postorder(root,res,returnSize);
return res;
}
//后
void postorder(struct TreeNode*root,int *res,int*returnSize){
if(root==NULL){
return;
}
postorder(root->left,res,returnSize);
res[(*returnSize)++]=root->val;
postorder(root->right,res,returnSize);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
int*res=(int*)malloc(sizeof(int)*100);
*returnSize=0;
postorder(root,res,returnSize);
return res;
}
题目总结
递归三部曲。
同样的题目
题目描述
如上
题目解答
//迭代法
int* preorderTraversal(struct TreeNode* root, int* returnSize) {
if(root==NULL){
*returnSize=0;
return NULL;
}
int *res=(int*)malloc(sizeof(int)*1200);
*returnSize=0;
int count=0;
//迭代法
struct TreeNode *stack[1200];
int top=0;
stack[0]=root;
while(top>=0){
struct TreeNode*node=stack[top--];
res[(*returnSize)++]=node->val;
if(node->right){
stack[++top]=node->right;
}
if(node->left){
stack[++top]=node->left;
}
}
return res;
}
//后序
int* postorderTraversal(struct TreeNode* root, int* returnSize) {
if(root==NULL){
*returnSize=0;
return NULL;
}
int*res=(int*)malloc(sizeof(int)*100);
*returnSize=0;
struct TreeNode*stack[1000];
int top=0;
stack[top]=root;
while(top>=0){
struct TreeNode *node=stack[top];
top--;
res[(*returnSize)++]=node->val;
if(node->left){
stack[++top]=node->left;
}
if(node->right){
stack[++top]=node->right;
}
}
int left=0;
int right=*returnSize-1;
int temp;
while(left<right){
temp= res[left];
res[left++]=res[right];
res[right--]=temp;
}
return res;
}
//中序
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
if(root==NULL){
*returnSize=0;
return NULL;
}
*returnSize=0;
int*res=(int*)malloc(sizeof(int)*100);
struct TreeNode*stack[100];
int top=0;
//stack[top]=root;
struct TreeNode*node=root;
while(top>0||node){
if(node){
stack[top++]=node;
node=node->left;
}else{
node=stack[--top];
res[(*returnSize)++]=node->val;
node=node->right;
}
}
return res;
}
题目总结
用数组加top来模拟栈操作。