1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

vector<vector<int> > levelOrderBottom(TreeNode *root) {
    vector<vector<int> > result;
    preOrder(root, 0, result);

    size_t size = result.size();
    for (size_t i = 0; i < size/2; ++i) {
        result[i].swap(result[size-1-i]);
    }

    return result;
}

void preOrder(TreeNode *n, int level, vector<vector<int> > &result) {
    if (n == NULL) return;

    if (level >= result.size()) {
        result.resize(level+1);
    }

    result[level].push_back(n->val);

    preOrder(n->left, level+1, result);
    preOrder(n->right, level+1, result);
}
View Program Text


Test Status