题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
递归实现二叉树前、中、后序遍历
注意:
三者的区别就是处理根节点的时间
代码
/** * 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<>> */ // 前序遍历 vector<int> pre; vector<int> mid; vector<int> after; vector<vector<int>> res; // 前序遍历 void preOrders(const TreeNode* root){ if(root==nullptr){ return ; } pre.push_back(root->val); preOrders(root->left); preOrders(root->right); } // 中序遍历 void midOrders(TreeNode* root){ if(root==nullptr){ return ; } midOrders(root->left); mid.push_back(root->val); midOrders(root->right); } // 后序遍历 void afterOrders(TreeNode* root){ if(root==nullptr){ return ; } afterOrders(root->left); afterOrders(root->right); after.push_back(root->val); } vector<vector<int> > threeOrders(TreeNode* root) { // write code here preOrders(root); midOrders(root); afterOrders(root); res.push_back(pre); res.push_back(mid); res.push_back(after); return res; } };