题解 | #实现二叉树先序,中序和后序遍历#
实现二叉树先序,中序和后序遍历
http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362
用最基本的前序,中序,后续,然后传入数组引用,注意递归返回值,注意函数调用
class Solution { public: /** * * @param root TreeNode类 the root of binary tree * @return int整型vector<vector<>> */ vector<vector<int> > threeOrders(TreeNode* root) { // write code here vector<vector<int> > results; vector<int> pre; pre_order(root,pre); results.push_back(pre); vector<int> in; in_order(root,in); results.push_back(in); vector<int> pos; pos_order(root,pos); results.push_back(pos); return results; } void pre_order(TreeNode* root, vector<int> &a){ if(!root){ return; } a.push_back(root->val); pre_order(root->left,a); pre_order(root->right,a); } void in_order(TreeNode* root, vector<int> &a){ if(!root){ return; } in_order(root->left,a); a.push_back(root->val); in_order(root->right,a); } void pos_order(TreeNode* root, vector<int> &a){ if(!root){ return; } pos_order(root->left,a); pos_order(root->right,a); a.push_back(root->val); } };
算法解析 文章被收录于专栏
这里主要是算法岗的自我思路总结