Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree [1,null,2,3]
,
1 \ 2 / 3
return [1,3,2]
.
用的递归方法,提示上说递归方法太普通了,尝试用迭代的方法做。(0ms)
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * struct TreeNode *left; 6 * struct TreeNode *right; 7 * }; 8 */ 9 /** 10 * Return an array of size *returnSize. 11 * Note: The returned array must be malloced, assume caller calls free(). 12 */ 13 void inorder(int *rst,struct TreeNode *root,int *size) 14 { 15 if(root == NULL) return ; 16 inorder(rst,root->left,size); 17 rst[(*size)++] = root->val; 18 inorder(rst,root->right,size); 19 } 20 int* inorderTraversal(struct TreeNode* root, int* returnSize) { 21 if(root == NULL) return root; 22 23 int *rst = malloc(sizeof(int) * 10000); 24 if(rst == NULL) return NULL; 25 26 *returnSize = 0; 27 inorder(rst,root,returnSize); 28 29 return rst; 30 }