leetcode-94-树题-二叉树的中序遍历

题目

1.png

解法

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
/**
* 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> res;
inorderTraversalCore(root, res);
return res;
}

// 迭代
void inorderTraversalCore(TreeNode *root, vector<int> &res){
stack<TreeNode *> store;
TreeNode *curr = root;
while(curr || !store.empty()){
while(curr){
store.push(curr);
curr = curr->left;
}
curr = store.top();
store.pop();
res.push_back(curr->val);
curr = curr->right;
}
}

递归
void inorderTraversalCore(TreeNode *root, vector<int> &res){
if(!root) return;
inorderTraversalCore(root->left, res);
res.push_back(root->val);
inorderTraversalCore(root->right, res);
}
};