Leetcode 107 Binary Tree Level Order Traversal II

2018-01-12 14:55:57 浏览数 (1)

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

代码语言:javascript复制
    3
   / 
  9  20
    /  
   15   7

return its bottom-up level order traversal as:

代码语言:javascript复制
[
  [15,7],
  [9,20],
  [3]
]

二叉树层序遍历,利用之前的代码,输出的时候reverse一下就可以了。

代码语言:javascript复制
/**
 * 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) {
        vector<vector<int>> res;  
        vector<int> temp;  
        queue<TreeNode*> q,q2;  
        q.push(root);  
        while(!q.empty() || !q2.empty())  
        {  
            if(q.empty())  
            {  
                swap(q,q2);  
                res.push_back(temp);  
                temp.clear();  
            }  
            TreeNode* first=q.front();  
            q.pop();  
            if(!first)continue;  
            temp.push_back(first->val);  
            q2.push(first->left);  
            q2.push(first->right);  
        }  
        reverse(res.begin(),res.end());
        return res;
    }
};

0 人点赞