Skip to content

Commit 054c3e6

Browse files
committed
Create Binary_Tree_Preorder_Traversal.cc
using Morris traversal algorithm
1 parent 5316231 commit 054c3e6

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

Binary_Tree_Preorder_Traversal.cc

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
};

0 commit comments

Comments
 (0)