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;
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章