File tree Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Expand file tree Collapse file tree 1 file changed +37
-0
lines changed Original file line number Diff line number Diff line change 1+ /* *
2+ * Definition for binary tree
3+ * struct TreeNode {
4+ * int val;
5+ * TreeNode *left;
6+ * TreeNode *right;
7+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8+ * };
9+ */
10+ class Solution {
11+ public:
12+ vector<int > preorderTraversal (TreeNode *root) {
13+ // IMPORTANT: Please reset any member data you declared, as
14+ // the same Solution instance will be reused for each test case.
15+ vector<int > ret;
16+ TreeNode *cur = root, *tmp = NULL ;
17+ while (cur) {
18+ if (!cur->left ) {
19+ ret.push_back (cur->val );
20+ cur = cur->right ;
21+ } else {
22+ tmp = cur->left ;
23+ while (tmp->right && tmp->right != cur)
24+ tmp = tmp->right ;
25+ if (!tmp->right ) {
26+ tmp->right = cur;
27+ ret.push_back (cur->val );
28+ cur = cur->left ;
29+ } else {
30+ tmp->right = NULL ;
31+ cur = cur->right ;
32+ }
33+ }
34+ }
35+ return ret;
36+ }
37+ };
You can’t perform that action at this time.
0 commit comments