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]

]

 

/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

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

 * };

 */

class Solution {

public:

    vector<vector<int> > levelOrderBottom(TreeNode *root) {

        vector<vector<TreeNode*> > list;

        vector<vector<int> > result;

        if(root==NULL)

            return result;

        vector<TreeNode*> level;

        level.push_back(root);

        list.push_back(level);

        while(level.size()>0)

        {

            vector<TreeNode*> newlevel;

            for(int i=0;i<level.size();i++)

            {

                if(level[i]->left!=NULL) newlevel.push_back(level[i]->left);

                if(level[i]->right!=NULL) newlevel.push_back(level[i]->right);

            }

            list.push_back(newlevel);

            level=newlevel;

        }

        

        for(int i=0;i<list.size()-1;i++)

        {

            vector<int> v;

            for(int j=0;j<list[list.size()-i-2].size();j++)

                v.push_back(list[list.size()-i-2][j]->val);

            result.push_back(v);

        }

        return result;

    }

};

 

你可能感兴趣的:(binary)