//====================先序遍历=======================
class Solution {
public:
vector<int> res;
stack<TreeNode*> st;
while (root) {
res.push_back(root->val);
st.push(root);
root = root->left;
}
while (!st.empty()) {
auto node = st.top();
st.pop();
node = node->right;
while (node) {
res.push_back(node->val);
st.push(node);
node = node->left;
}
}
return res;
};
//====================中序遍历=======================
class Solution {
public:
vector<int> res;
stack<TreeNode*> st;
while (root) {
st.push(root);
root = root->left;
}
while (!st.empty()) {
auto node = st.top();
st.pop();
res.push_back(node->val);
node = node->right;
while (node) {
st.push(node);
node = node->left;
}
}
return res;
};
//====================后序遍历=======================
class Solution {
public:
stack<TreeNode*>st;
vector<int>a;
if (root == nullptr) return a; //判断必须加,不然提交报错
st.push(root);
while (!st.empty())
{
root = st.top();
st.pop();
a.push_back(root->val);
if (root->left) st.push(root->left);
if (root->right) st.push(root->right);
}
reverse(a.begin(), a.end()); //转换!!!
return a;
};
二叉树遍历(前序、中序、后序)stack
最新推荐文章于 2022-03-23 20:55:22 发布
这篇博客详细介绍了三种树的遍历方法:先序遍历、中序遍历和后序遍历。通过C++代码展示了如何使用栈来实现这些遍历策略,包括将节点值压入结果数组、处理左右子节点的过程。这些遍历算法是数据结构和算法学习中的基础内容,对于理解和操作树形数据结构至关重要。
摘要由CSDN通过智能技术生成