8000 2 · zwxalgorithm/leetcode-1@fd3228a · GitHub
[go: up one dir, main page]

Skip to content

Commit fd3228a

Browse files
committed
2
1 parent 941c2d7 commit fd3228a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
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+
vector<int> result;
14+
TreeNode* node = root;
15+
while (node) {
16+
if (node->left == NULL) {
17+
result.push_back(node->val);
18+
node = node->right;
19+
} else {
20+
TreeNode* next = node->left;
21+
while (next->right && next->right != node) {
22+
next = next->right;
23+
}
24+
if (next->right == NULL) {
25+
next->right = node;
26+
result.push_back(node->val);
27+
node = node->left;
28+
} else {
29+
next->right = NULL;
30+
node = node->right;
31+
}
32+
}
33+
}
34+
return result;
35+
}
36+
};

0 commit comments

Comments
 (0)
0