leetcode[145]:Binary Tree Postorder Traversal

Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes’ values.

For example:
Given binary tree {1,#,2,3},

   1
    \
     2
    /
   3

return [3,2,1].

Note: Recursive solution is trivial, could you do it iteratively?

/**
 * 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* postorderTraversal(struct TreeNode* root, int* returnSize) {
    struct TreeNode stack[1000];
    struct TreeNode *tmp;
    int i=0;
    int res[100000]={0},*result; 
    int k=0;
    if(!root) {*returnSize=k;return NULL;}

    tmp=root;

    while(1)
    {
        if(!tmp->left && !tmp->right)
        {
            res[k++] = tmp->val;
            if(i==0) break;
            tmp=&stack[--i];
            continue;
        }
        stack[i++] = *tmp;
        if( tmp->left )
        {
            tmp=stack[i-1].left;
            stack[i-1].left=NULL;
            continue;
        }
        if( tmp->right)
        {
           tmp=stack[i-1].right;
           stack[i-1].right=NULL;
        }

    }
    * returnSize =k;
    result= (int*)malloc(sizeof(int*)*k);
    for(i=0;i<k;i++)
    {
        result[i]=res[i];
    }
    return result;
}

尋找葉子,先左後右,壓棧時將左子樹賦空,左子樹爲空時,將右子樹賦空,葉子可以輸出了。

發佈了85 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章