二叉树的前序、中序、后序遍历(迭代)
二叉树的通用中序遍历方法(迭代):
思路来源:https://leetcode-cn.com/problems/binary-tree-inorder-traversal/solution/yan-se-biao-ji-fa-yi-chong-tong-yong-qie-jian-ming/
/**
* 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) {
stack<pair<TreeNode*, int>> st;
vector<int> ans;
st.push({root,0});
while(!st.empty()){
auto node = st.top().first;
auto color = st.top().second;
st.pop();
if(node == nullptr){
continue;
}
if(color == 0){
st.push(make_pair(node->right,0));
st.push(make_pair(node,1));
st.push(make_pair(node->left,0));
}else{
ans.push_back(node->val);
}
}
return ans;
}
};