107. Binary Tree Level Order Traversal II

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

 解题思路:记录每行的节点数,now表示当前层的节点数,pre表示上一层的节点数,每次出队的的时候让pre--,直到减为0,将now赋值给pre,同时让now继续为0.

/**
 * 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) {
        if(!root)return {};
        vector<vector<int>>ans;
        vector<int>level;
        queue<TreeNode* >q;
        q.push(root);
        int now=0,pre=1;
        while(!q.empty()){
            root=q.front();
            level.push_back(root->val);
            q.pop();
            pre--;
            if(root->left)q.push(root->left),now++;
            if(root->right)q.push(root->right),now++;
            if(pre==0){
                ans.push_back(level);
                level.clear();
                pre=now;
                now=0;
            }
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};

 

posted @ 2017-02-25 20:43  Tsunami_lj  阅读(111)  评论(0编辑  收藏  举报