-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinary_Tree_Preorder_Traversal.cpp
More file actions
74 lines (74 loc) · 2.76 KB
/
Binary_Tree_Preorder_Traversal.cpp
File metadata and controls
74 lines (74 loc) · 2.76 KB
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
class Solution
{
public:
/*Binary Tree Preorder Traversal , 递归版本*/
vector<int> preorderTraversal(TreeNode *root)
{
vector<int> result;
if (root == nullptr) return result;
result.push_back(root->val);
vector<int> left = preorderTraversal(root->left);
result.insert(result.end(), left.begin(), left.end());
vector<int> right = preorderTraversal(root->right);
result.insert(result.end(), right.begin(), right.end());
return result;
}
/*非递归,用栈*/
vector<int> preorderTraversal_v2(TreeNode *root)
{
stack<TreeNode*> stack_tree;
vector<int> result;
if (root == nullptr)
return result;
stack_tree.push(root);
while (!stack_tree.empty())
{
TreeNode * ptr_tree = stack_tree.top();
result.push_back(ptr_tree->val);
stack_tree.pop();
if (ptr_tree->right != nullptr)
stack_tree.push(ptr_tree->right);
if (ptr_tree->left != nullptr)
stack_tree.push(ptr_tree->left);
}
return result;
}
// LeetCode, Binary Tree Preorder Traversal
// Morris 先序遍历,时间复杂度 O(n),空间复杂度 O(1)
vector<int> preorderTraversal(TreeNode *root)
{
vector<int> result;
TreeNode *cur, *prev;
cur = root;
while (cur != nullptr)
{
if (cur->left == nullptr)
{
result.push_back(cur->val);
prev = cur; /* cur 刚刚被访问过 */
cur = cur->right;
}
else
{
/* 查找前驱 */
TreeNode *node = cur->left;
while (node->right != nullptr && node->right != cur)
node = node->right;
if (node->right == nullptr) /* 还没线索化,则建立线索 */
{
result.push_back(cur->val); /* 仅这一行的位置与中序不同 */
node->right = cur;
prev = cur; /* cur 刚刚被访问过 */
cur = cur->left;
}
else /* 已经线索化,则删除线索 */
{
node->right = nullptr;
/* prev = cur; 不能有这句, cur 已经被访问 */
cur = cur->right;
}
}
}
return result;
}
};