107. Binary Tree Level Order Traversal II

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

My Solution

/**
 * 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> levelOrderBottom(TreeNode* root) {
        vector> ans;
        vector temp;
        queue qu;
        TreeNode* p = root;
        
        if (p){
            qu.push(p);
            qu.push(NULL);
        }
        
        while(!qu.empty()){
            while(qu.front()){
                p = qu.front();
                if (p->left){
                    qu.push(p->left);
                }
                if (p->right){
                    qu.push(p->right);
                }
                temp.push_back(p->val);
                qu.pop();
            }
            qu.pop();
            if (!temp.empty()){
                ans.push_back(temp);
            }
            temp.clear();
            if (qu.empty()){
                break;
            }
            qu.push(NULL);
        }
        
        vector t;
        for (int i = 0; i < ans.size()/2; i++){
            t = ans[i];
            ans[i] = ans[ans.size()-i-1];
            ans[ans.size()-i-1] = t;
        }
        
        return ans;
    }
}

你可能感兴趣的:(107. Binary Tree Level Order Traversal II)