方法一:迭代法
/**
* 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;
TreeNode* cur = root;
stack<TreeNode*> stk;
while(cur||stk.size())
{
while(cur)
{
stk.push(cur);
cur = cur->left;
}
cur = stk.top();
res.push_back(cur->val);
stk.pop();
cur = cur->right;
}
return res;
}
};
方法二:颜色标记法:
/**
* 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 {
typedef pair<TreeNode*, int> PTI;
public:
vector<int> order;
vector<int> inorderTraversal(TreeNode* root) {
//数据包类型
stack<PTI> stk;
stk.push({root, 0});
while (stk.size()) {
auto [t, color] = stk.top(); stk.pop();
if (t == nullptr) continue;
if (color == 0) {
stk.push({t->right, 0});
stk.push({t, 1});
stk.push({t->left, 0});
} else {
order.push_back(t->val);
}
}
return order;
}
};