题解 | 二叉树的中序遍历
二叉树的中序遍历
https://www.nowcoder.com/practice/0bf071c135e64ee2a027783b80bf781d
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型一维数组 * @return int* returnSize 返回数组行数 */ //中序遍历 void printnode(struct TreeLinkNode* node, int* num, int* returnSize) { if (node == NULL) { return; } printnode(node->left, num, returnSize); num[(*returnSize)++] = node->val; printnode(node->right, num, returnSize); } //为了避免越界,我的思路是先计算节点,避免资源的浪费 void countNodes(struct TreeNode* node, int* count) { if (node == NULL) { return; } countNodes(node->left, count); (*count)++; countNodes(node->right, count); } int* inorderTraversal(struct TreeNode* root, int* returnSize ) { // write code here countNodes(root, returnSize); int* ret = (int*)malloc(sizeof(int) * (*returnSize)); *returnSize=0; printnode(root, ret, returnSize); return ret; }