题意:给出一个二叉树,输出他的中序遍历,不要用递归的写法
思想:就是使用stack去写的,每个节点都要2次进栈,第一次进为false,第二次为true。
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
// write code here
vector<int> result;
if(root == nullptr) return result;
stack<pair<TreeNode* , bool> > mid;
mid.push(make_pair(root, false));
pair<TreeNode* , bool> now;
while(!mid.empty())
{
now = mid.top();
mid.pop();
if(now.second == true) {
result.push_back(now.first->val);
} else {
if(now.first->right != nullptr) mid.push({now.first->right,false});
mid.push({now.first,true});
if(now.first->left != nullptr) mid.push({now.first->left,false});
}
}
return result;
}
};