递归实现二叉树的前序、中序和后序遍历
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 the root of binary tree * @return int整型vector<vector<>> */ void preOrder(vector<int>& ans, TreeNode* root) { if (root != nullptr) { ans.push_back(root->val); preOrder(ans, root->left); preOrder(ans, root->right); } } void midOrder(vector<int>& ans, TreeNode* root) { if (root != nullptr) { midOrder(ans, root->left); ans.push_back(root->val); midOrder(ans, root->right); } } void postOrder(vector<int>& ans, TreeNode* root) { if (root != nullptr) { postOrder(ans, root->left); postOrder(ans, root->right); ans.push_back(root->val); } } vector<vector<int> > threeOrders(TreeNode* root) { // write code here vector<vector<int> > threeorders; vector<int> pre, mid, post; preOrder(pre, root); midOrder(mid, root); postOrder(post, root); threeorders.push_back(pre); threeorders.push_back(mid); threeorders.push_back(post); return threeorders; } };