前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【leetcode刷题】T119-二叉树的层次遍历 II

【leetcode刷题】T119-二叉树的层次遍历 II

作者头像
木又AI帮
发布2019-07-22 16:26:29
2760
发布2019-07-22 16:26:29
举报
文章被收录于专栏:木又AI帮

木又连续日更第71天(71/100)


木又的第119篇leetcode解题报告

二叉树类型第9篇解题报告

leetcode第107题:二叉树的层次遍历 II

https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/


【题目】

给定一个二叉树,返回其节点值自底向上的层次遍历。(即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)

代码语言:javascript
复制
例如:
给定二叉树 [3,9,20,null,null,15,7],
    3
   / \
  9  20
    /  \
   15   7
返回其自底向上的层次遍历为:

[
  [15,7],
  [9,20],
  [3]
]

【思路】

本题与【T115-二叉树的层次遍历】几乎一样,最后将结果进行翻转即可。

【代码】

python版本

代码语言:javascript
复制
# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:
            return []
        res = []
        tmp = []
        ls1 = [root]
        ls2 = []
        while len(ls1) != 0 or len(ls2) != 0:
            if len(ls1) == 0:
                ls1 = copy.copy(ls2)
                ls2 = []
                res.append(tmp)
                tmp = []
            node = ls1.pop(0)
            tmp.append(node.val)
            if node.left:
                ls2.append(node.left)
            if node.right:
                ls2.append(node.right)
        res.append(tmp)
        return res[::-1]

C++版本

代码语言: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;
        if(!root)
            return res;
        vector<int> num;
        queue<TreeNode*> tmp1;
        tmp1.push(root);
        queue<TreeNode*> tmp2;
        TreeNode* p;
        while(!tmp1.empty() || !tmp2.empty()){
            // tmp1为空,tmp2不为空,则交换tmp1和tmp2
            if(tmp1.empty()){
                while(!tmp2.empty()){
                    tmp1.push(tmp2.front());
                    tmp2.pop();
                }
                res.insert(res.begin(), num);
                num.erase(num.begin(), num.end());
            }
            p = tmp1.front();
            tmp1.pop();
            num.push_back(p->val);
            if(p->left)
                tmp2.push(p->left);
            if(p->right)
                tmp2.push(p->right);
        }
        res.insert(res.begin(), num);
        return res;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2019-07-17,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 木又AI帮 微信公众号,前往查看

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

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

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