【Binary Tree Level Order Traversal II 】cpp

题目:

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 a binary tree node.
 * 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> > ret;
            if (!root) return ret;
            vector<int> tmp_ret;
            deque<TreeNode *> currLevel, nextLevel;
            currLevel.push_back(root);
            while ( !currLevel.empty() )
            {
                while ( !currLevel.empty() )
                {
                    TreeNode * tmp = currLevel.front();
                    currLevel.pop_front();
                    tmp_ret.push_back(tmp->val);
                    if ( tmp->left ) nextLevel.push_back(tmp->left);
                    if ( tmp->right ) nextLevel.push_back(tmp->right);
                }
                ret.push_back(tmp_ret);
                tmp_ret.clear();
                std::swap(currLevel, nextLevel);
            }
            std::reverse(ret.begin(), ret.end());
            return ret;
    }
};

tips:

Binary Tree Level Order Traversal的基础上加一个reverse即可。

============================================

第二次过这道题,直接用reverse的路子了。

/**
 * Definition for a binary tree node.
 * 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> > ret;
            queue<TreeNode*> curr;
            queue<TreeNode*> next;
            if ( root ) curr.push(root);
            while ( !curr.empty() )
            {
                vector<int> tmp;
                while ( !curr.empty() )
                {
                    tmp.push_back(curr.front()->val);
                    if ( curr.front()->left ) next.push(curr.front()->left);
                    if ( curr.front()->right ) next.push(curr.front()->right);
                    curr.pop();
                }
                ret.push_back(tmp);
                std::swap(next, curr);
            }
            std::reverse(ret.begin(), ret.end());
            return ret;
    }
};

 

posted on 2015-05-14 10:18  承续缘  阅读(143)  评论(0编辑  收藏  举报

导航