[leetcode]94. 二叉树的中序遍历

1.题目:
给定一个二叉树,返回它的中序 遍历。

示例:
输入: [1,null,2,3]
   1
    \
     2
    /
   3
输出: [1,3,2]

2.代码:

//非递归法:
/**
 * 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().
 */
/*
栈初试化top=0;
入栈[top++]=x;
出栈x=[--top];
top指向下一个空位置;
*/

typedef struct TreeNode* Tree;

typedef struct {
    Tree* array;                    								  //存放指针的数组
    int top;
}Stack;

int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    int *r=NULL;
    *returnSize=0;
    Stack *s=malloc(sizeof(Stack));
    s->array=(Tree*)malloc(sizeof(Tree));                             //初始化
    s->top=0;
    while(s->top||root){
        if(root){
            s->array=(Tree*)realloc(s->array,sizeof(Tree)*(s->top+1));//加一个
            s->array[s->top++]=root;  //*******
            root=root->left;		  //*******
        }
        else{
            root=s->array[--s->top];  //*******
            r=(int *)realloc(r,sizeof(int)*((*returnSize)+1));        //加一个
            r[*returnSize]=root->val;
            (*returnSize)+=1;
            root=root->right;		  //*******
        }
    }
    return r;
}

3.知识点:

1.中序遍历非递归法
2.栈的使用:

猜你喜欢

转载自blog.csdn.net/MJ_Lee/article/details/88540502