题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
https://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * }; */ #include <vector> class Solution { public: /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 the root of binary tree * @return int整型vector<vector<>> */ vector<int> v1; vector<int> v2; vector<int> v3; vector<vector<int> > threeOrders(TreeNode* root) { // write code here if(root!=nullptr){ preorder(root); midorder(root); postorder(root); } vector<vector<int>> ans; ans.push_back(v1); ans.push_back(v2); ans.push_back(v3); return ans; } void preorder(TreeNode* root){ if(root==nullptr){ return ; } v1.push_back(root->val);//先向vector容器中插入中,插入顺序是中左右 preorder( root->left); preorder(root->right); } void midorder(TreeNode* root){ if(root==nullptr){ return ; } midorder( root->left); v2.push_back(root->val); midorder(root->right); } void postorder(TreeNode* root){ if(root==nullptr){ return ; } postorder( root->left); postorder(root->right); v3.push_back(root->val); } };