Leetcode94.二叉数的中序遍历练习
初始代码
问题:未完成
/*** 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* n=(int*)malloc(sizeof(int)*(returnSize));int m=0;struct TreeNode* new=root;struct TreeNode* current=new;while(m<returnSize){ new=root;while(new){ while(new->left){new=new->left;current=new;}n[m++]=new->val;if(new->right==NULL)new=NULL;else new=new->right;}new=current;}
}
反思问题:
1.尝试过迭代与递归两种方法(对于迭代,知道要找到每个节点的父节点,但没想到用栈来存储,用下标的改变来回到父节点的位置;对于递归,知道“左 根 右”的顺序,但仅在意找到节点位置,没有想到可以直接在递归函数中就记录下每个节点的数据),对中序遍历的底层逻辑不熟练,无法把自己的逻辑思路转换成算法思维。
2.returnSize为指针,理解错意义
最终AC代码
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* inorderTraversal(struct TreeNode* root, int* returnSize) {int top=-1,count=0;struct TreeNode** stack=(struct TreeNode**)malloc(sizeof(struct TreeNode*)*100);struct TreeNode* current=root;while(top!=-1||current!=NULL){while(current!=NULL){stack[++top]=current;current=current->left;}current=stack[top--];count++;current=current->right;}*returnSize=count;int* n=(int*)malloc(sizeof(int)*(count));top=-1;current=root;int m=0;while(top!=-1||current!=NULL){while(current!=NULL){stack[++top]=current;current=current->left;}current=stack[top--];n[m++]=current->val;current=current->right;}return n;
}
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().*/
void me(struct TreeNode* root,int* n,int* count)
{if(root==NULL)return;me(root->left,n,count);n[(*count)++]=root->val;me(root->right,n,count);
}
void sum(struct TreeNode* root,int *returnSize)
{if(root==NULL) return;sum(root->left,returnSize);(*returnSize)++;//注意指针++与指针指向数据++的区别sum(root->right,returnSize);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {struct TreeNode* current=root;*returnSize=0;sum(current,returnSize);int num=*returnSize;int* n=(int*)malloc(sizeof(int)*num);int count=0;me(current,n,&count);//注意第三个形参类型return n;
}