forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
2416c12
commit 76417bc
Showing
2 changed files
with
63 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test bst_preorder.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
|
||
struct TreeNode { | ||
int val; | ||
struct TreeNode *left; | ||
struct TreeNode *right; | ||
}; | ||
|
||
/** | ||
** Return an array of size *returnSize. | ||
** Note: The returned array must be malloced, assume caller calls free(). | ||
**/ | ||
static int* preorderTraversal(struct TreeNode* root, int* returnSize) { | ||
if (root == NULL) { | ||
return NULL; | ||
} | ||
|
||
int cap = 10000, count = 0; | ||
int *results = malloc(cap * sizeof(int)); | ||
struct TreeNode **stack = malloc(cap / 16 * sizeof(*stack)); | ||
struct TreeNode **top = stack; | ||
struct TreeNode *node = root; | ||
|
||
while (node != NULL || top != stack) { | ||
if (node == NULL) { | ||
node = *--top; | ||
} | ||
|
||
results[count++] = node->val; | ||
if (node->right != NULL) { | ||
*top++ = node->right; | ||
} | ||
node = node->left; | ||
} | ||
|
||
*returnSize = count; | ||
return results; | ||
} | ||
|
||
int main(int argc, char **argv) | ||
{ | ||
struct TreeNode root, node1, node2; | ||
root.val = 1; | ||
node1.val = 2; | ||
node2.val = 3; | ||
root.left = NULL; | ||
root.right = &node1; | ||
node1.left = &node2; | ||
node1.right = NULL; | ||
node2.left = NULL; | ||
node2.right = NULL; | ||
|
||
int i, count = 0; | ||
int *results = preorderTraversal(&root, &count); | ||
for (i = 0; i < count; i++) { | ||
printf("%d ", results[i]); | ||
} | ||
printf("\n"); | ||
return 0; | ||
} |