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],
]

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.


OJ's Binary Tree Serialization:

The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.

Here's an example:

   1
  / \
 2   3
    /
   4
    \
     5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}".

思路:此题和Binary Tree Level Order Traversal是类似的,就是输出的顺序改变了,在上题的基础之上,我将顺序颠倒输出就可以了。

/**
 * 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<int> > result;
        if(root==NULL)
            return result;
        queue<TreeNode *> pTree;
        vector<int> data;
        pTree.push(root);
        int count=1;
        while(!pTree.empty())
        {
            data.clear();
            int temp_count=0;
            for(int i=0;i<count;i++)
            {
                TreeNode *tn=pTree.front();
                pTree.pop();
                data.push_back(tn->val);
                if(tn->left)
                {
                    pTree.push(tn->left);
                    temp_count++;
                }
                if(tn->right)
                {
                    pTree.push(tn->right);
                    temp_count++;
                }
            }
            count=temp_count;
            result.push_back(data);
        }
        vector<vector<int> > ret;
        vector<vector<int> >::iterator iter=result.end()-1;
        for(;iter>=result.begin();iter--)
        {
            ret.push_back(*iter);
        }
        return ret;
    }
};

 

 

 

posted @ 2014-03-18 21:29  Awy  阅读(168)  评论(0编辑  收藏  举报