-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-inorder-traversal.cpp
More file actions
93 lines (82 loc) · 2.55 KB
/
binary-tree-inorder-traversal.cpp
File metadata and controls
93 lines (82 loc) · 2.55 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
// 三刷,自己做出来了
// inorder中序遍历,即先左子树,然后自己,最后右子树
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
auto t=root;
while(!s.empty() || t){
while(t){
s.push(t);
t=t->left;
}
t=s.top();
s.pop();
res.push_back(t->val);
t=t->right;
}
return res;
}
// 二刷,没有做出来
// 中序遍历是这样的顺序:left->root->right
// 感觉不是很好推导出来,暂时先背下来吧:
// 1.使用两种数据结构:stack和一个临时节点
// 2.while的循环条件是while(!s.empty() || t)
// 3.主体思想是先穷尽左子树,然后打印当前值,看看右子树,最后利用栈返回上层
vector<int> inorderTraversal2(TreeNode* root) {
vector<int> res;
if(!root) return res;
stack<TreeNode*> s;
TreeNode* t=root;
while(!s.empty() || t){
while(t){
s.push(t);
t=t->left;
}
t=s.top(),s.pop();
res.push_back(t->val);
t=t->right;
}
return res;
}
//迭代的方法。https://www.cnblogs.com/grandyang/p/4297300.html
vector<int> inorderTraversal1(TreeNode* root) {
vector<int> result;
stack<TreeNode*> s;
TreeNode* p=root;
while(p!=NULL || !s.empty()){
while(p){//左儿子优先
s.push(p);
p=p->left;
}
p=s.top();//没有更左的啦 就要中根啦
s.pop();
result.push_back(p->val);
p=p->right;//然后右儿子
}
return result;
}
//注意这种递归方法是没有意义的!!!
vector<int> inorderTraversal5(TreeNode* root) {
vector<int> result;
inorder(result,root);
return result;
}
void inorder(vector<int>& result,TreeNode* root){
if(!root) return;
if(root->left) inorder(result,root->left);
result.push_back(root->val);
if(root->right) inorder(result,root->right);
}
};