首页 > 代码库 > leetcode(144,94,145,102)中迭代版的二叉树的前、中、后、层级遍历
leetcode(144,94,145,102)中迭代版的二叉树的前、中、后、层级遍历
//前序遍历
class Solution{ public: vector<int> preorderTraversal(TreeNode *root){ vector<int> res; stack<TreeNode*> s; TreeNode* p = root; if(!p) return res; s.push(p); while(!s.empty()){ p = s.top(); s.pop(); res.push_back(p->val); if(p->right) s.push(p->right); if(p->left) s.push(p->left); } return res; } }; //中序遍历 class Solution{ public: vector<int> inorderTraversal(TreeNode* root){ vector<int> res; stack<TreeNode*> s; TreeNode* p = root; while(p || !s.empty()){ if(p != nullptr){ s.push(p); p = p->left; }else{ p = s.top(); res.push_back(p->val); s.pop(); p = p-> right(); } } return res; } }; //后序遍历 class Solution { public: vector<int> postorderTraversal(TreeNode* root) { vector<int> res; TreeNode* p = root; if (!p) return res; stack<pair<TreeNode*, int>> s; s.push(make_pair(p, 0)); while (!s.empty()) { int times = s.top().second; TreeNode* p = s.top().first; s.pop(); if (times == 0) { s.push(make_pair(p, 1)); if (p->right) s.push(make_pair(p->right, 0)); if (p->left) s.push(make_pair(p->left, 0)); } if (times == 1) { res.push_back(p->val); } } return res; } }; //层级遍历 class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> res; if(root == nullptr) return res; TreeNode* p = root; queue<TreeNode*> current,next; vector<int> levelElem; current.push(p); while(!current.empty()){ while(!current.empty()){ p = current.front(); current.pop(); levelElem.push_back(p->val); if(p->left) next.push(p->left); if(p->right) next.push(p->right); } res.push_back(levelElem); levelElem.clear(); swap(current,next); } return res; } };
leetcode(144,94,145,102)中迭代版的二叉树的前、中、后、层级遍历
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。