class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<pair<TreeNode*, int> > stk;
stk.push((make_pair(root, 0)));
while(!stk.empty()) {
auto [node, type] = stk.top();
stk.pop();
if(node == nullptr) continue;
if(type == 0) {
stk.push(make_pair(node->right, 0));
stk.push(make_pair(node, 1));
stk.push(make_pair(node->left, 0));
}
else result.emplace_back(node->val);
}
return result;
}
};
力扣上发现的 空间换智商 的中序遍历,记录一下。
前序和后序只需要交换一下stk.push顺序即可。