題目描述
給定一個二叉樹,返回它的中序 遍歷。
示例:
輸入: [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;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* inorderTraversal(struct TreeNode* root, int* returnSize){
*returnSize = 0;
if(!root)
return NULL;
int ts = treesize(root);
int* p = (int *)malloc(sizeof(int)*ts);
midsort(root, p, returnSize);
return p;
}
int treesize(struct TreeNode* t) //遞歸求出樹的結點數
{
if(!t)
return 0;
return treesize(t->left) + treesize(t->right) +1;
}
void midsort(struct TreeNode* root, int* num, int* returnSize)
{
if(!root)
return NULL;
midsort(root->left, num, returnSize); //遍歷左子樹
num[(*returnSize)++] = root->val; //將此結點的值存入數組
midsort(root->right, num, returnSize); //遍歷右子樹
}
注:returnSize在函數返回前必須賦值,否則當傳入空樹時會發生load of null pointer of type ‘const int’ 錯誤。