forked from lolosssss/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path144_binary_tree_preorder_traversal.c
64 lines (55 loc) · 1.22 KB
/
144_binary_tree_preorder_traversal.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/**
* Description : Binary Tree Preorder Traversal
* Given a binary tree, return the preorder traversal of its
* nodes' values.
* Author : Evan Lau
* Date : 2016/05/13
*/
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
int* preorderTraversal(struct TreeNode *root, int *returnSize)
{
if (!root)
{
*returnSize = 0;
return NULL;
}
int left = 0;
int right = 0;
int *leftRet = NULL;
int *rightRet = NULL;
if (root->left)
{
leftRet = preorderTraversal(root->left, &left);
}
if (root->right)
{
rightRet = preorderTraversal(root->right, &right);
}
int len = left + right + 1;
*returnSize = len;
int *ret = (int *)malloc(sizeof(int) * len);
for (int i = 0; i < len; i++)
{
if (i == 0)
{
*(ret + i) = root->val;
}
else if (i > 0 && i <= left)
{
*(ret + i) = *(leftRet + i - 1);
}
else if (i > left)
{
*(ret + i) = *(rightRet + i - left - 1);
}
}
free(leftRet);
free(rightRet);
return ret;
}