LeetCode:二叉樹的中序遍歷
阿新 • • 發佈:2020-09-09
給定一個二叉樹,返回它的中序 遍歷。
輸入: [1,null,2,3]
1
\
2
/
3
輸出: [1,3,2]
遞迴方法
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; if (!root) return result; if (root->left) { vector<int> tmp = inorderTraversal(root->left); result.insert(result.end(), tmp.begin(), tmp.end()); } result.push_back(root->val); if (root->right) { vector<int> tmp = inorderTraversal(root->right); result.insert(result.end(), tmp.begin(), tmp.end()); } return result; } };
遞迴的本質就是壓棧,用棧代替遞迴來迭代
先序遍歷
class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; //儲存結果 stack<TreeNode*> call; //呼叫棧 if (root != nullptr) call.push(root); //首先介入root節點 while (!call.empty()) { TreeNode* t = call.top(); call.pop(); //訪問過的節點彈出 if (t != nullptr) { if (t->right) call.push(t->right); //右節點先壓棧,最後處理 if (t->left) call.push(t->left); call.push(t); //當前節點重新壓棧(留著以後處理),因為先序遍歷所以最後壓棧 call.push(nullptr); //在當前節點之前加入一個空節點表示已經訪問過了 } else //空節點表示之前已經訪問過了,現在需要處理除了遞迴之外的內容 { res.push_back(call.top()->val); //call.top()是nullptr之前壓棧的一個節點,也就是上面call.push(t)中的那個t call.pop(); //處理完了,第二次彈出節點(徹底從棧中移除) } } return res; } };
中序後序都類似