NC45-實現二叉樹的先序、中序和後序遍歷
阿新 • • 發佈:2021-02-05
技術標籤:牛客題霸
題目描述
分別按照二叉樹先序,中序和後序列印所有的節點。
示例1
輸入
{1,2,3}
返回值
[[1,2,3],[2,1,3],[2,3,1]]
題解:
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { private: vector<int> pre,mid,post; public: /** * * @param root TreeNode類 the root of binary tree * @return int整型vector<vector<>> */ vector<vector<int> > threeOrders(TreeNode* root) { // write code here vector<vector<int>> res; if(root == nullptr) return res; //vector<int> pre,mid,post; preOrder(root); midOrder(root); postOrder(root); res = {pre,mid,post}; return res; } void preOrder(TreeNode* rot) { if(rot == nullptr) return; pre.push_back(rot->val); preOrder(rot->left); preOrder(rot->right); } void midOrder(TreeNode* rot) { if(rot == nullptr) return; midOrder(rot->left); mid.push_back(rot->val); midOrder(rot->right); } void postOrder(TreeNode* rot) { if(rot == nullptr) return; postOrder(rot->left); postOrder(rot->right); post.push_back(rot->val); } };