赞
踩
1、前序遍历:根左右
2、中序遍历:左根右
3、后序遍历:左右根
1、问题概述:二叉树中序遍历
2、示例
示例 1:
输入:root = [1,null,2,3] 输出:[1,3,2]示例 2:
输入:root = [] 输出:[]示例 3:
输入:root = [1] 输出:[1]
3、分析
(1)返回的是数组形式:先用malloc申请一片连续存储空间
(2)初始化存储空间,将*returnSize=0
(3)进行递归
(4)返回数组
4、代码
- void leftbl(struct TreeNode* root,int* returnSize,int *result){
- if(root!=NULL){
- // 中序遍历
- leftbl(root->left,returnSize,result); // 左
- result[(*returnSize)++]=root->val; // 根
- leftbl(root->right,returnSize,result); // 右
-
- // 前序遍历
- /**
- result[(*returnSize)++]=root->val; // 根
- leftbl(root->left,returnSize,result); // 左
- leftbl(root->right,returnSize,result); // 右
- */
-
- // 后序遍历
- /**
- leftbl(root->left,returnSize,result); // 左
- leftbl(root->right,returnSize,result); // 右
- result[(*returnSize)++]=root->val; // 根
- */
- }
- }
-
-
- int* inorderTraversal(struct TreeNode* root, int* returnSize) {
- // 先申请一片内存空间
- int *result=malloc(sizeof(int)*1000);
-
- // 初始化(将内存存储空间设置为0)
- *returnSize=0;
-
- leftbl(root,returnSize,result);
-
- return result;
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。