题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
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> first; vector<int> mid; vector<int> last; vector<vector<int> > threeOrders(TreeNode* root) { // write code here firstorder(root); midorder(root); lastorder(root); vector<vector<int>> threeorders; threeorders.push_back(first); threeorders.push_back(mid); threeorders.push_back(last); return threeorders; } void firstorder(TreeNode *root){ if(root!=NULL){ first.push_back(root->val); if(root->left!=NULL) firstorder(root->left); if(root->right!=NULL) firstorder(root->right); } return; } void midorder(TreeNode *root){ if(root!=NULL){ if(root->left!=NULL) midorder(root->left); mid.push_back(root->val); if(root->right!=NULL) midorder(root->right); } return; } void lastorder(TreeNode *root){ if(root!=NULL){ if(root->left!=NULL) lastorder(root->left); if(root->right!=NULL) lastorder(root->right); last.push_back(root->val); } return; } };
采用递归的方法进行,意料之外的时间最快,内存却较大,有点疑惑,观看大部分题解都是采用同样的递归方法,为何会有此不同,望解惑!