diff --git a/094_binary_tree_inorder_traversal/Makefile b/094_binary_tree_inorder_traversal/Makefile new file mode 100644 index 0000000..d3ae6df --- /dev/null +++ b/094_binary_tree_inorder_traversal/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test bst_inorder_traversal.c diff --git a/094_binary_tree_inorder_traversal/bst_inorder_traversal.c b/094_binary_tree_inorder_traversal/bst_inorder_traversal.c new file mode 100644 index 0000000..8730457 --- /dev/null +++ b/094_binary_tree_inorder_traversal/bst_inorder_traversal.c @@ -0,0 +1,45 @@ +#include +#include + + struct TreeNode { + int val; + struct TreeNode *left; + struct TreeNode *right; + }; + +static void traverse(struct TreeNode *node, int *result, int *count) +{ + if (node->left != NULL) { + traverse(node->left, result, count); + } + + result[*count] = node->val; + (*count)++; + + if (node->right != NULL) { + traverse(node->right, result, count); + } +} + +/** + * * Return an array of size *returnSize. + * * Note: The returned array must be malloced, assume caller calls free(). + * */ +int* inorderTraversal(struct TreeNode* root, int* returnSize) { + if (root == NULL) { + *returnSize = 0; + return NULL; + } + int count = 0; + int *result = malloc(5000 * sizeof(int)); + traverse(root, result, &count); + *returnSize = count; + return result; +} + +int main() +{ + int count = 0; + inorderTraversal(NULL, &count); + return 0; +}