首页 > 代码库 > LeetCode[Tree]: Binary Tree Level Order Traversal II

LeetCode[Tree]: Binary Tree Level Order Traversal II

Given a binary tree, return the bottom-up level order traversal of its nodes‘ values. (ie, from left to right, level by level from leaf to root).

这个简单的问题可以这样解决:利用LeetCode[Tree]: Binary Tree Level Order Traversal相同的方法得到自顶向下的层序遍历结果之后,将结果翻转即可。也可以插入的时候不从尾部插,而从头部插。

我的C++代码实现如下:

vector<vector<int> > levelOrderBottom(TreeNode *root) {
    vector<vector<int> > result;
    vector<int> level;

    queue<TreeNode *> levelQ;
    if (root) levelQ.push(root);        
    while (!levelQ.empty()) {
        level.clear();
        int size = levelQ.size();
        for (int i = 0; i < size; ++i) {
            TreeNode *node = levelQ.front();
            levelQ.pop();

            level.push_back(node->val);

            if (node->left ) levelQ.push(node->left );
            if (node->right) levelQ.push(node->right);
        }

        result.insert(result.begin(), level);
    }

    return result;
}


LeetCode[Tree]: Binary Tree Level Order Traversal II