题解 | #二叉树的前序、中序、后序遍历#

实现二叉树先序,中序和后序遍历

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<vector<int> > threeOrders(TreeNode* root) {
        vector<vector<int> > resVec;
        resVec.push_back( preVisit(root) ); 
        resVec.push_back( inVisit(root) );
        resVec.push_back( postVisit(root) );
        return resVec;
    }
  	//将每种遍历结果存在一个vector中
    vector<int> preVisit(TreeNode * root)
    {
        static vector<int> preVec;
        if(root == nullptr) return preVec;
        preVec.push_back(root->val);
        preVisit(root->left);
        preVisit(root->right);
        return preVec;
    }
    vector<int> inVisit(TreeNode * root)
    {
        static vector<int> inVec;
        if(root == nullptr) return inVec;
        inVisit(root->left);
        inVec.push_back(root->val);
        inVisit(root->right);
         return inVec;
    }
    vector<int> postVisit(TreeNode * root)
    {
        static vector<int> posVec;
        if(root == nullptr) return posVec;
        postVisit(root->left);
        postVisit(root->right);
        posVec.push_back(root->val);
        return posVec;
    }
};
全部评论

相关推荐

Natrium_:这时间我以为飞机票
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务