For example:
Given binary tree
{1,#,2,3}
,1 \ 2 / 3
return
[1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what
"{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.這是recursive的版本
iterative 可以參考preorder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /** * 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) { //int size=*returnSize; if(root==NULL)return NULL; int lesize=0,risize=0,*le=NULL,*ri=NULL; le=inorderTraversal(root->left,&lesize); ri=inorderTraversal(root->right,&risize); int *ans=malloc(sizeof(int)*(lesize+1+risize)); *returnSize = lesize+1+risize; for(int i =0;i<lesize;i++){ if(le!=NULL)ans[i]=le[i]; } ans[lesize]=root->val; for(int j=0;j<risize;j++){ if(ri!=NULL)ans[lesize+1+j]=ri[j]; } return ans; } |
沒有留言:
張貼留言