解题思路

递归实现。另外,先序并不是树的逐层展示,树的逐层展示用的是广度优先搜索。

代码

/**
 * 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>> rets;

        preorderSort(root, rets);
        inorderSort(root, rets);
        postorderSort(root, rets);
        return rets;
    }

private:
    void preorderSortBase(TreeNode* root, vector<int>& ret) {
        if (!root)
            return;
        ret.push_back(root->val);
        preorderSortBase(root->left, ret);
        preorderSortBase(root->right, ret);
    }

    void preorderSort(TreeNode* root, vector<vector<int>>& rets) {
        vector<int> ret;
        preorderSortBase(root, ret);
        rets.push_back(ret);
    }

    void inorderSortBase(TreeNode* root, vector<int>& ret) {
        if (!root)
            return;
        inorderSortBase(root->left, ret);
        ret.push_back(root->val);
        inorderSortBase(root->right, ret);
    }

    void inorderSort(TreeNode* root, vector<vector<int>>& rets) {
        vector<int> ret;
        inorderSortBase(root, ret);
        rets.push_back(ret);
    }

    void postorderSortBase(TreeNode* root, vector<int>& ret) {
        if (!root)
            return;
        postorderSortBase(root->left, ret);
        postorderSortBase(root->right, ret);
        ret.push_back(root->val);
    }

    void postorderSort(TreeNode* root, vector<vector<int>>& rets) {
        vector<int> ret;
        postorderSortBase(root, ret);
        rets.push_back(ret);
    }
};