[LeetCode 107] Binary Tree Level Order Traversal II

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/

http://www.lintcode.com/zh-cn/problem/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).

For example:
Given binary tree {3,9,20,#,#,15,7},

    3

   / \

  9  20

    /  \

   15   7

return its bottom-up level order traversal as:

[

  [15,7],

  [9,20],

  [3]

]
#include <list>

/**

 * Definition of TreeNode:

 * class TreeNode {

 * public:

 *     int val;

 *     TreeNode *left, *right;

 *     TreeNode(int val) {

 *         this->val = val;

 *         this->left = this->right = NULL;

 *     }

 * }

 */

 

 

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

        list<vector<int>> lstVec;

        queue<TreeNode *> q;

        

        q.push(root);

        q.push(NULL);

        while (!q.empty() && q.front() != NULL) {

            vector<int> vecSubRet;

            

            while (true) {

                TreeNode *node = q.front();

                q.pop();

                

                if (node == NULL) {

                    q.push(NULL);

                    break;

                }

                

                if (node -> left) {

                    q.push(node -> left);

                }

                

                if (node -> right) {

                    q.push(node -> right);

                }

                

                vecSubRet.push_back(node -> val);

            }

            

            lstVec.push_front(vecSubRet);

        }

        

        vector<vector<int>> ret(lstVec.begin(), lstVec.end());

        return ret;

    }

};

你可能感兴趣的:(LeetCode)