前序遍历
leetocde144
- 思路:由于是要前序遍历存储在result数组中,那么存入栈的顺序就应该是相反的。
class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> result;
if (root != nullptr) st.push(root);
while(!st.empty())
{
TreeNode* node = st.top();
if(node != nullptr)
{
st.pop();
if(node->right != nullptr) st.push(node->right);
if(node->left != nullptr) st.push(node->left);
st.push(node);
st.push(nullptr);
}else
{
st.pop();
node = st.top();
st.pop();
result.push_back(node->val);
}
}
return result;
}
};
中序遍历
- 思路:由于是要中序遍历存储在result数组中的顺序为左中右,那么存入栈的顺序就应该是相反的,从而在弹出栈时能够以左中右的顺序弹出。
leetcode94
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
if(root != nullptr) st.push(root);
while(!st.empty())
{
TreeNode* node = st.top();
if(node != nullptr)
{
st.pop();
if(node->right != nullptr) st.push(node->right);
st.push(node);
st.push(nullptr);
if(node->left != nullptr) st.push(node->left);
}else
{
st.pop();
result.push_back(st.top()->val);
st.pop();
}
}
return result;
}
};
后序遍历
- 思路:由于是要后序遍历存储在result数组中的顺序为左右中,那么存入栈的顺序就应该是相反的,从而在弹出栈时能够以左右中的顺序弹出。
leetcode145
class Solution {
public:
vector<int> postorderTraversal(TreeNode* root) {
vector<int> result;
stack<TreeNode*> st;
if(root != nullptr) st.push(root);
while(!st.empty())
{
TreeNode* node = st.top();
if(node != nullptr)
{
st.pop();
st.push(node);
st.push(nullptr);
if(node->right != nullptr) st.push(node->right);
if(node->left != nullptr) st.push(node->left);
}else
{
st.pop();
result.push_back(st.top()->val);
st.pop();
}
}
return result;
}
};