107. Binary Tree Level Order Traversal II /BFS

题目描述

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,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

return its bottom-up level order traversal as:

[
  [15,7],
  [9,20],
  [3]
]

分析

树的层序遍历,当然是得用BFS算法。为了将每一层单独放置到一个vector容器中,可在BFS的循环体中逐层入队并逐层输出。

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> ans;
        if(root==NULL) return ans;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int cnt=q.size(); //当前层的结点数
            vector<int> temp(cnt);
            for(int i=0;i<cnt;i++){
                auto now=q.front();
                q.pop();
                temp[i]=now->val;
                if(now->left) q.push(now->left);
                if(now->right) q.push(now->right);
            }            
            ans.push_back(temp);            
        }
        reverse(ans.begin(),ans.end()); //题目要求自底向上
        return ans;
    }
};
发布了103 篇原创文章 · 获赞 9 · 访问量 4693

猜你喜欢

转载自blog.csdn.net/weixin_43590232/article/details/104476714
今日推荐