1 Star 0 Fork 0

丁旭升/cpp代码

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
二叉树非递归版.txt 2.98 KB
一键复制 编辑 原始数据 按行查看 历史
丁旭升 提交于 2022-10-28 09:50 . 二叉树前中后非递归版遍历
https://leetcode.cn/problems/binary-tree-preorder-traversal/submissions/
/**
* 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> preorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> v;
TreeNode* cur=root;
while(cur || !st.empty())
{
//左子树
while(cur)
{
st.push(cur);
v.push_back(cur->val);
cur=cur->left;
}
// 2、左路节点的右子树需要访问
TreeNode* top=st.top();
st.pop();
//右子树
cur=top->right; // 子问题访问右子树
}
return v;
}
};
https://leetcode.cn/problems/binary-tree-inorder-traversal/submissions/
/**
* 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<TreeNode*> st;
vector<int> v;
TreeNode* cur = root;
while (cur || !st.empty())
{
// 开始访问一棵树
//1、左路节点
while (cur)
{
st.push(cur);
cur = cur->left;
}
// 2、左路节点的右子树需要访问. 根要存入。
TreeNode* top = st.top();
st.pop();
v.push_back(top->val);
cur = top->right; // 子问题访问右子树
}
return v;
}
};
https://leetcode.cn/problems/binary-tree-postorder-traversal/submissions/
/**
* 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> postorderTraversal(TreeNode* root) {
stack<TreeNode*> st;
vector<int> v;
TreeNode* cur=root, *prev=nullptr;
while(cur || !st.empty())
{
//左树
while(cur)
{
st.push(cur);
cur=cur->left;
}
TreeNode* top=st.top();
//判断出栈。和存数据
if(top->right==nullptr || top->right==prev) //prev上一次pop的对象
{
st.pop();
prev=top;
v.push_back(top->val);
}
else //右子树不为空或者未访问
{
//访问右子树
cur=top->right;
}
}
return v;
}
};
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/ding-xushengyun/code.git
[email protected]:ding-xushengyun/code.git
ding-xushengyun
code
cpp代码
master

搜索帮助