题目描述:
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解答:
/**
* 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().
*/
#define LEN 0xff
void func(struct TreeNode* root, int* res, int* index)
{
if(NULL == root) return;
func(root->left, res, index);
res[(*index)++] = root->val;
func(root->right, res, index);
}
int* inorderTraversal(struct TreeNode* root, int* returnSize)
{
*returnSize = 0;
int* res = malloc(sizeof(int) * LEN);
func(root, res, returnSize);
return res;
}
运行结果: