leetcode144 二叉樹前序遍歷與中序遍歷的不同
阿新 • • 發佈:2018-11-22
二叉樹中序遍歷
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { TreeNode* cur=root; vector<int> res; // res.push_back(cur->val); stack<TreeNode*> st; while(cur||!st.empty()){ if(cur){ st.push(cur); cur=cur->left; }else{ cur=st.top(); res.push_back(cur->val); st.pop(); /* if(cur->right){ cur=cur->right; }else{ cur=st.top(); }*/ cur=cur->right; } } return res; } };
中序遍歷 左 中 右 一直往左走,走到不能走後,就回溯
前序遍歷:
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> st; TreeNode* cur=root; while(!st.empty()||!cur){ if(cur){ res.push_back(cur->val); st.push(cur); cur=cur->left; }else{ st.pop(); //錯誤程式碼 cur=st.top()->right // } } return res; } };
我腦中想的是這樣:
前左右 ,很正常的思維
實際應該是這樣:
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; stack<TreeNode*> st; TreeNode* cur=root; while(!st.empty()||!cur){ if(cur){ res.push_back(cur->val); st.push(cur); cur=cur->left; }else{ if(!st.empty()){ cur=st.top()->right; st.pop(); } } } return res; } };