Binary Tree Levelorder 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).

分析:

属于基本题,可以做到5分钟,1次过。

记得用到reverse(iter, iter)这函数时候,include "algorithm"这个包。

解法:

class Solution {
    /**
     * @param root : The root of binary tree.
     * @return : buttom-up level order a list of lists of integer
     */
public:
    vector<vector<int>> levelOrderBottom(TreeNode *root) {
        // write your code here
        if (root == NULL) {
            return vector<vector<int> >();
        }
        vector<vector<int> > res;
        queue<TreeNode* > Q;
        Q.push(root);
        while (!Q.empty() ) {
            int size = Q.size();
            vector<int> level;
            for (int i = 0; i < size; i++) {
                TreeNode* temp = Q.front();
                Q.pop();
                level.push_back(temp->val);
                if (temp->left != NULL) {
                    Q.push(temp->left);
                }
                if (temp->right != NULL) {
                    Q.push(temp->right);
                }
            }
            res.push_back(level);
        }
        reverse(res.begin(), res.end() );
        return res;
    }
};

results matching ""

    No results matching ""