(必背)二叉樹的前中後序遍歷(利用棧)
阿新 • • 發佈:2021-01-23
技術標籤:leetcode刷題
二叉樹的前序遍歷(利用棧)
1.首先將根節點壓入棧
2.棧中的首元素出棧,然後先將其右節點壓入棧中,再將棧中的左節點壓入棧中(如果左右節點分別存在的話)
3.重複步驟2直到棧為空
class Solution { public: stack<TreeNode*> st; vector<int> preorderTraversal(TreeNode* root) { vector<int> res; if(root == nullptr) return res; st.push(root); while(!st.empty()){ TreeNode* tp = st.top(); st.pop(); res.push_back(tp->val); if(tp->right) st.push(tp->right); if(tp->left) st.push(tp->left); } return res; } };
二叉樹的中序遍歷(利用棧)
遍歷是按照“左根右”的順序來進行的,按照"右根左"的方法進行遍歷,然後翻轉一下就可以得到答案
class Solution { public: stack<TreeNode*> st; vector<int> inorderTraversal(TreeNode* root) { vector<int> res; while(root || st.size()){ while(root){ st.push(root); root = root->right; } root = st.top(); res.push_back(root->val); st.pop(); root = root->left; } reverse(res.begin(),res.end()); return res; } };
二叉樹的後序遍歷(利用棧)
遍歷是按照“左右根”的順序來進行的,按照"根右左"的方法進行遍歷,然後翻轉一下結果就可以得到答案
class Solution { public: stack<TreeNode*> st; vector<int> postorderTraversal(TreeNode* root) { vector<int> res; while(root || st.size()){ while(root){ res.push_back(root->val); st.push(root); root = root->right; } root = st.top()->left; st.pop(); } reverse(res.begin(),res.end()); return res; } };