欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > LeetCode94:二叉树的中序遍历

LeetCode94:二叉树的中序遍历

2024/10/23 13:24:13 来源:https://blog.csdn.net/2301_80423531/article/details/143088524  浏览:    关键词:LeetCode94:二叉树的中序遍历

文章目录

  • 😊1.题目
  • 😉2.解法
    • 1.递归
    • 2.迭代

😊1.题目

尝试一下该题
在这里插入图片描述

😉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().*/void Inorder(struct TreeNode* root,int *res, int* returnSize){if(root){Inorder(root->left, res, returnSize);res[(*returnSize)++] = root->val;Inorder(root->right,res,returnSize);}}
int* inorderTraversal(struct TreeNode* root, int* returnSize){*returnSize = 0;int *res = (int*)malloc(sizeof(int)*101);Inorder(root,res,returnSize);return res;
}

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().*/
#define MAX 101
typedef struct stack{int top;struct TreeNode *data[MAX];
}SqStack;SqStack* InitStack(){SqStack *S = (SqStack*)malloc(sizeof(SqStack));S->top = -1;return S;
}bool IsEmpty(SqStack *S){return S->top == -1;
}void push(SqStack *S, struct TreeNode *p){S->data[++S->top] = p;
}void pop(SqStack *S, struct TreeNode **p){*p = S->data[S->top--];
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {*returnSize = 0;int *res =(int*)malloc(sizeof(int)*101);SqStack *S;S= InitStack();struct TreeNode *cur = root;while(cur || !IsEmpty(S)){if(cur){push(S,cur);cur = cur->left;}else{pop(S,&p);res[(*returnSize)++] = cur->val;cur = cur->right;}}return res;}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com