LeetCode 94. 二叉樹的中序遍歷(C語言)

給定一個二叉樹,返回它的中序 遍歷。

示例:

輸入: [1,null,2,3]
   1
    \
     2
    /
   3

輸出: [1,3,2]

進階: 遞歸算法很簡單,你可以通過迭代算法完成嗎?

方法一: 採用遞歸算法,按照左根右的順序遍歷二叉樹

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
/**
 * 定義一個數組res用來存儲遍歷的節點,
 * 其中returnSize 使用來儲存當前數組位置的, 
 * returnSize 即爲當前位置
 */
void inorder(struct TreeNode* root, int* returnSize, int* res){
    if(root != NULL){
        inorder(root->left, returnSize, res);
        res[(*returnSize)++] = root->val;
        inorder(root->right, returnSize, res);
    }
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    int* res = (int*)malloc(sizeof(int)*1000);
    *returnSize = 0;
    inorder(root, returnSize, res);
    return res;
}

方法二: 採用非遞歸算法,不定義棧結構,而是利用一個數組和指針模擬棧操作

 int* inorderTraversal(struct TreeNode* root, int* returnSize) {
     int *res = (int*)malloc(sizeof(int)*1000);
     struct TreeNode* stack[1000];
     int top = -1; //棧頂指針
     int size = 0;
     while(root || top != -1) {
         while(root != NULL){
             stack[++top] = root;  //進棧操作
             root = root->left;
         }
        if(top != -1){
            root = stack[top--];  //出棧操作
            res[size++] = root->val; //訪問當前結點
            root = root->right;
        }
     }
    *returnSize = size;
     return res;
 }

方法三: 採用非遞歸算法,定義棧結構及其相應的方法,進而進行操作。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
typedef struct stack *Stack;
typedef struct node *Node;
struct stack
{
    Node top;
};
struct node
{
    Node next;
    struct TreeNode *n;
};
void push(Stack s,struct TreeNode *n1)
{
    Node a=(Node)malloc(sizeof(*a));
    a->n=n1;
    a->next=s->top;
    s->top=a;
}
struct TreeNode *pop(Stack s)
{
    struct TreeNode *a=s->top->n;
    s->top=s->top->next;
    return a;
}
int* inorderTraversal(struct TreeNode* root, int* returnSize) {
    int *res=(int*)malloc(10000*sizeof(int));
    *returnSize=0;
    
    Stack s=(Stack)malloc(sizeof*s);
    s->top=NULL;
    
    struct TreeNode *k=root;
    while(s->top||k)
    {
        if(k)
        {
            push(s,k);
            k=k->left;
        }
        else 
        {
            k=pop(s);
            res[(*returnSize)++]=k->val;
            k=k->right;
        }
    }
    return res;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章