二叉树遍历(前序、中序、后序)stack
2023-09-11 14:19:17 时间
//====================先序遍历=======================
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;
};
相关文章
- 二叉树中序遍历(迭代)
- 二叉树
- Java实现 LeetCode 814 二叉树剪枝 (遍历树)
- Java实现 LeetCode 731 我的日程安排表 II(二叉树)
- Java实现 LeetCode 543 二叉树的直径
- Java实现 LeetCode 257 二叉树的所有路径
- Java实现 LeetCode 107 二叉树的层次遍历 II(二)
- Lintcode---二叉树的层次遍历
- (剑指Offer)面试题6:重建二叉树
- LeetCode(103): 二叉树的锯齿形层次遍历
- LeetCode-226. 翻转二叉树【递归】
- ( “树” 之 前中后序遍历) 145. 二叉树的后序遍历 ——【Leetcode每日一题】
- 华为OD机试 - 二叉树层序遍历(Java & JS & Python)
- 【平衡二叉树】平衡二叉树的概念及相关操作
- 前序遍历和中序遍历树构造二叉树
- 二叉树的建立与遍历
- [LeetCode] 110. Balanced Binary Tree ☆(二叉树是否平衡)
- 数据结构 - 求二叉树中结点的最大距离(C++)
- 一步一步写算法(之排序二叉树)
- 数据结构(6)二叉树
- 一步一步写算法(之排序二叉树)
- 【Leetcode刷题Python】103. 二叉树的锯齿形层序遍历
- LeetCode 102. 二叉树的层序遍历
- 【LeetCode】103. 二叉树的锯齿形层序遍历
- go语言|数据结构:二叉树(3)拷贝、镜像和对称