您的位置:首页 > 新闻 > 资讯 > 木渎网站制作_哪个网站推广产品好_网站信息查询_seo工作是什么意思

木渎网站制作_哪个网站推广产品好_网站信息查询_seo工作是什么意思

2025/2/25 19:25:54 来源:https://blog.csdn.net/Buling_0/article/details/145826061  浏览:    关键词:木渎网站制作_哪个网站推广产品好_网站信息查询_seo工作是什么意思
木渎网站制作_哪个网站推广产品好_网站信息查询_seo工作是什么意思

二叉树的递归遍历

力扣题目链接-前序遍历
力扣题目链接-后序遍历
力扣题目链接-中序遍历

题目描述

给你二叉树的根节点,分别前序/后序/中序遍历输出节点。

算法描述

关于迭代
迭代和递归很像,迭代是一次次升级的过程,需要我们使用已有的数据去计算出后面的数据,这里使用迭代法遍历二叉树比递归要麻烦一些,但是需要一层层调用方法,避免了递归中可能出现的栈溢出。

解题思路

这里其实前序和后续比较简单,主要是中序遍历比较麻烦。

题解

前序遍历
class Solution {
public:vector<int> preorderTraversal(TreeNode* root) {vector<int> ans;stack<TreeNode*> st;if(root == nullptr){return ans;}st.push(root);while(!st.empty()){TreeNode* cur = st.top();ans.push_back(cur->val);st.pop();if(cur->right){st.push(cur->right);}if(cur->left){st.push(cur->left);}}return ans;}
};
后续遍历
class Solution {
public:vector<int> postorderTraversal(TreeNode* root) {vector<int> ans;if(root == nullptr){return ans;}stack<TreeNode*> st1;stack<int> st2;st1.push(root);while(!st1.empty()){TreeNode* cur = st1.top();st2.push(cur->val);st1.pop();if(cur->left){st1.push(cur->left);}if(cur->right){st1.push(cur->right);}}while(!st2.empty()){ans.push_back(st2.top());st2.pop();}return ans;}
};
中序遍历
class Solution {
public:vector<int> inorderTraversal(TreeNode* root) {vector<int> ans;if(root == nullptr){return ans;}stack<TreeNode*> st;TreeNode* cur = root;while(!st.empty() || cur != nullptr){if(cur != nullptr){st.push(cur);cur = cur->left;}else{cur = st.top();st.pop();ans.push_back(cur->val);cur = cur->right;}}return ans;}
};

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com