代码拉取完成,页面将自动刷新
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;
}
};
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。