C语言非递归+栈的方法。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
//非递归,利用栈。
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
struct TreeNode** stack=NULL,*pre=root;
*returnSize=0;
int i=0,j=0,*nums=NULL;
stack = (struct TreeNode **)malloc(sizeof(struct TreeNode *));
nums = (int *)malloc((j+1)*sizeof(int));
while(i||pre)
{
if(pre){
stack = (struct TreeNode **)realloc(stack, sizeof(struct TreeNode *)*i+1);
stack[i++]=pre;
pre=pre->left;
}
else{
pre=stack[--i];
nums = (int *)realloc(nums, sizeof(int)*(j+1));
nums[j++]=pre->val;
*returnSize+=1;
pre=pre->right;
}
}
return nums;
}
这种方法,比较好理解,只不过因为*returnSize这个指针类型,导致经常出错。
递归方法。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int *nums=NULL,i=0;
void inorder(struct TreeNode* root)
{
nums = (int *)realloc(nums, sizeof(int)*(i+1));
if(root){
inorder(root->left);
nums[i++]=root->val;
inorder(root->right);
}
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
*returnSize=0;
i=0;
if(root==NULL)
return NULL;
else
{
nums = (int *)malloc(sizeof(int));
inorder(root);
*returnSize=i;
return nums;
}
}
经过两天的调试,这个递归算法终于让我解出来了
在调试过程中发现几个问题。
1、全局变量,不知为何发生了变化,为不影响局部数据,需重新赋值。
2、malloc,realloc等动态划分的时候,有指针变量一定要动态分配内存,不然一定会有栈溢出错误。
2016/2/2