107. Binary Tree Level Order Traversal II /BFS

Title Description

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]
]

analysis

Tree traversal sequence, of course, starting BFS algorithm. In order to place each layer in a separate container vector, layer by layer may be enqueued in the loop and the BFS output layer by layer.

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;
    }
};
Published 103 original articles · won praise 9 · views 4693

Guess you like

Origin blog.csdn.net/weixin_43590232/article/details/104476714