leetcode[145]:Binary Tree Postorder Traversal

来源:互联网 发布:php 订单号生成算法 编辑:程序博客网 时间:2024/05/16 02:03

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;}

寻找叶子,先左后右,压栈时将左子树赋空,左子树为空时,将右子树赋空,叶子可以输出了。

0 0
原创粉丝点击