leetcode, LC42: 二叉树程序遍历 ii

1 题目描述

给定一个二叉树,返回该二叉树由底层到顶层的层序遍历,(从左向右,从叶子节点到根节点,一层一层的遍历)

2 解题思路

bfs

3 代码实现

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @return int整型vector>
     */
    vector<vector<int> > levelOrderBottom(TreeNode* root) {
        vector<vector<int>> res;
        if(root == NULL) return res;
        
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            vector<int> cur_level;
            int queue_size = q.size();
            for(int i = 0; i < queue_size; i++){
                if(q.front()->left != NULL) q.push(q.front()->left);
                if(q.front()->right != NULL) q.push(q.front()->right);
                cur_level.push_back(q.front()->val);
                q.pop();
            }
            res.push_back(cur_level);
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

4 运行结果

运行时间:3ms
占用内存:400k

你可能感兴趣的:(leetcode,二叉树,leetcode,数据结构,算法)