题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
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<>> */ void preOrder(TreeNode* root,vector<int>& ret) { if (!root) { return; } ret.push_back(root->val); preOrder(root->left,ret); preOrder(root->right,ret); } void inOrder(TreeNode* root,vector<int>& ret) { if (!root) { return; } inOrder(root->left,ret); ret.push_back(root->val); inOrder(root->right,ret); } void nextOrder(TreeNode* root,vector<int>& ret) { if (!root) { return; } nextOrder(root->left,ret); nextOrder(root->right,ret); ret.push_back(root->val); } vector<vector<int> > threeOrders(TreeNode* root) { vector<int> ret1; vector<int> ret2; vector<int> ret3; preOrder(root,ret1); inOrder(root,ret2); nextOrder(root,ret3); vector<vector<int> > ret; ret.push_back(ret1); ret.push_back(ret2); ret.push_back(ret3); return ret; } };