中序遍历

递归法

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {//递归
public:
void Inorder(TreeNode *root, vector<int> &res){
if(!root){
return;
}
Inorder(root->left,res);
res.push_back(root->val);
Inorder(root->right,res);
}
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
Inorder(root,res);
return res;
}


};

迭代法

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {//迭代
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode*> st;
while(root!=nullptr || !st.empty()){
while(root!=nullptr){
st.push(root);
root=root->left;
}//这一步算到最后会得到root=null
root = st.top();//这个即原根节点的最左下的节点
res.push_back(root->val);
st.pop();
root=root->right;

}
return res;
}


};

Morris/莫里斯中序遍历

c1b589b5fc7facd1a847c9f5bab407765222ee2d9e1a887a9e5d61cc9e94dfc6-3

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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {//Morris/莫里斯中序遍历
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
TreeNode *pre;
while(root!=nullptr){
if(root->left!=nullptr){
pre = root->left;
while(pre->right!=nullptr){
pre= pre->right;
}
pre->right = root;
TreeNode *temp = root;
root=root->left;
temp->left=nullptr;
}
else{
res.push_back(root->val);
root = root->right;
}


}

return res;
}


};