前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode 107 Binary Tree Level Order Traversal II

Leetcode 107 Binary Tree Level Order Traversal II

作者头像
triplebee
发布2018-01-12 14:55:57
4600
发布2018-01-12 14:55:57
举报

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;
    }
};
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-10-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档