-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path144. Binary Tree Preorder Traversal
99 lines (78 loc) · 2.24 KB
/
144. Binary Tree Preorder Traversal
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//C
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int* preorderTraversal(struct TreeNode* root, int* returnSize){
int *preorder=NULL, *tmp=NULL, *plar=NULL, *prar=NULL;
int sl=0, sr=0, sz=0, sp=0;
struct TreeNode* pl;
struct TreeNode* pr;
if(root != NULL){
pl = root->left;
pr = root->right;
sz = 1;
preorder = malloc(sz*sizeof(int));
*preorder = root->val;
if(pl != NULL){
plar = preorderTraversal(pl, &sl);
if(plar != NULL){
sp = sz;
sz += sl;
tmp = realloc(preorder, sz*sizeof(int));
preorder = tmp;
memcpy(preorder+sp, plar, sl*sizeof(int));
free(plar);
}
}
if(pr != NULL){
prar = preorderTraversal(pr, &sr);
if(prar != NULL){
sp = sz;
sz += sr;
tmp = realloc(preorder, sz*sizeof(int));
preorder = tmp;
memcpy(preorder+sp, prar, sr*sizeof(int));
free(prar);
}
}
}
*returnSize = sz;
return preorder;
}
//c++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> order;
vector<int> tmp;
TreeNode *p_left, *p_right;
if(root != NULL){
p_left = root->left;
p_right = root->right;
order.push_back(root->val);
if(p_left != NULL){
tmp = preorderTraversal(p_left);
order.insert(order.end(), tmp.begin(), tmp.end());
}
if(p_right != NULL){
tmp = preorderTraversal(p_right);
order.insert(order.end(), tmp.begin(), tmp.end());
}
}
return order;
}
};