leetcode 107. Binary Tree Level Order Traversal II

Posted StrongYaYa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 107. Binary Tree Level Order Traversal II相关的知识,希望对你有一定的参考价值。

题目描述:

//利用队列 进行广度优先搜索

/**
 * 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(NULL == root)
            return ret;
        
        queue<TreeNode *> vi;
        
        vi.push(root);
        
        while(!vi.empty()){
            vector<int> v;
            for(int i = 0, n = vi.size(); i < n ; i++ ){
                TreeNode *tmp = vi.front();
                vi.pop();
                if(tmp->left != NULL)
                    vi.push(tmp->left);
                if(tmp->right != NULL)
                    vi.push(tmp->right);
                v.push_back(tmp->val);
            }
            ret.push_back(v);
        }
        reverse(ret.begin(),ret.end());
        return ret;
    }
};

 

以上是关于leetcode 107. Binary Tree Level Order Traversal II的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode107. Binary Tree Level Order Traversal II 解题报告

LeetCode_107. Binary Tree Level Order Traversal II

Leetcode 107 Binary Tree Level Order Traversal II

LeetCode107 Binary Tree Level Order Traversal II

Leetcode 107. Binary Tree Level Order Traversal II

LeetCode 107.Binary Tree Level Order Traversal II