【Leetcode】二叉树的层次遍历

题目:node

给定一个二叉树,返回其节点值自底向上的层次遍历。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)spa

 

例如:code

 

 

思路:采用宽度优先搜索。blog

时间复杂度:O(n)。n为节点的数量,遍历全部节点。it

空间复杂度:O(n)。建立一个vector容器存储全部节点值。io

/**
 * 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> > result;
        if (root == NULL)
            return result;
        
        queue<TreeNode*> q;
        q.push(root);
        
        while(!q.empty()) {
            int len = q.size();
            vector<int> temp;
            
            for (int i = 0; i < len; ++i) {
                TreeNode* node = q.front();
                q.pop();
                temp.push_back(node->val);
                
                if(node->left != NULL)
                    q.push(node->left);
                if(node->right != NULL)
                    q.push(node->right);
            }
            result.insert(result.begin(), temp);
        }
        return result;   
    }
};