LeetCode-Binary Tree Inorder Traversal

使用了两种方法对二叉树进行中序遍历,具体可以参考二叉树相关知识点总结

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
/**
* 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:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
inorder2(root,result);
return result;
}
void inorder1(TreeNode* root, vector<int>& result){
if(root==nullptr) return;
inorder1(root->left,result);
result.push_back(root->val);
inorder1(root->right,result);
}
void inorder2(TreeNode* root, vector<int>& result){
if(root==nullptr) return;
stack<TreeNode*> s;
TreeNode* n=root;
while(!s.empty() || n!=nullptr){
while(n!=nullptr){
s.push(n);
n=n->left;
}
if(!s.empty()){
n=s.top();
s.pop();
result.push_back(n->val);
n=n->right;
}
}
}
void inorder3(TreeNode* root, vector<int>& result){
if(root==nullptr) return;
stack<TreeNode*> s;
s.push(root);
TreeNode* n=root->left;
while(!s.empty() || n!=nullptr){
if(n!=nullptr){
s.push(n);
n=n->left;
}else{
n=s.top();
s.pop();
result.push_back(n->val);
n=n->right;
}

}
}
};