leetcode(144,94,145,102)中迭代版的二叉树的前中后层级遍历

Posted wxquare的学习笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)中迭代版的二叉树的前中后层级遍历的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode JS实现 二叉树(前中后层序)遍历(递归迭代法)

LeetCode JS实现 二叉树(前中后层序)遍历(递归迭代法)

LC 144. / 94. / 145. Binary Tree Preorder/ Inorder/ PostOrder Traversal

[二叉树专题]力扣144,94,145

LeetCode二叉树题总结(持续更新)

图解 二叉树的四种遍历