码迷,mamicode.com
首页 > 其他好文 > 详细

107. Binary Tree Level Order Traversal II(Tree, WFS)

时间:2015-10-04 15:50:27      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:

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

思路:使用两个队列完成层次搜索,结果存储在vector中。

若使用一个队列,也可完成层次遍历,只是不清楚遍历到哪个层次了。两个队列可以知道目前元素所在的层次。

/**
 * 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) {
        result.clear();
        if(!root) return result;
        
        vector<int> level;
        TreeNode * current;
        queue<TreeNode * > queToPop;
        queue<TreeNode * > queToPush;
        queToPop.push(root);
        while(!queToPop.empty())
        {
            while(!queToPop.empty())
            {
                current = queToPop.front();
                queToPop.pop();
                level.push_back(current->val);
                if(current->left)
                {
                    queToPush.push(current->left); //若使用一个队列,这里应该是queToPop.push(...),只要queToPop不为空,就继续pop和push
                }
                if(current->right)
                {
                    queToPush.push(current->right);
                }
            }
           
            result.push_back(level);
            level.clear();
            swap(queToPop, queToPush);
        }
        
        reverse(result.begin(), result.end()); //逆序vector的方法
        return result;
    }
private:
    vector<vector<int>> result;
};

 

107. Binary Tree Level Order Traversal II(Tree, WFS)

标签:

原文地址:http://www.cnblogs.com/qionglouyuyu/p/4854551.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!