1. 堆栈实现前序遍历
/**
* 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> preorderTraversal(TreeNode* root) {
if (root == nullptr) return vector<int>(0);
vector<int> ans(0);
stack<TreeNode*> st;
while (root || !st.empty())
{
while (root)
{
ans.push_back(root->val);
st.push(root);
root = root->left;
}
TreeNode *node = st.top();
st.pop();
root = node->right;
}
return ans;
}
};
2. 堆栈实现中序遍历
/**
* 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) {
if(root==nullptr) return vector<int>(0);
vector<int> ans(0);
stack<TreeNode*> st;
while(root || !st.empty())
{
while(root)
{
st.push(root);
root = root->left;
}
TreeNode *node = st.top();
ans.push_back(node->val);
st.pop();
root = node->right;
}
return ans;
}
};
3. 堆栈实现后序遍历
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
if (root == nullptr) return vector<int>(0);
vector<int> ans(0);
stack<TreeNode*> st;
TreeNode *lastViewed = nullptr; //记录上次输出的节点
//跳到最下边的左子树
while (root)
{
st.push(root);
root = root->left;
}
while (!st.empty())
{
//右子树为空或者上次访问过右子树时,输出此节点
if (st.top()->right == nullptr || st.top()->right == lastViewed)
{
ans.push_back(st.top()->val); //输出节点
lastViewed = st.top(); //这里对lastViewed赋值才有意义,因为这时才算真正输出了节点(即把节点放到ans里)
st.pop();
}
else
{
root = st.top()->right;//此时右子树不为空
while (root)
{
st.push(root);
root = root->left;
}
}
}
return ans;
}
};
参考文献:https://blog.youkuaiyun.com/zhangxiangDavaid/article/details/37115355