File tree Expand file tree Collapse file tree 1 file changed +36
-0
lines changed
BinaryTreePreorderTraversal Expand file tree Collapse file tree 1 file changed +36
-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
+ 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
+ };
You can’t perform that action at this time.
0 commit comments