美文网首页LeetCode
107. 二叉树的层次遍历 II

107. 二叉树的层次遍历 II

作者: 凌霄文强 | 来源:发表于2019-03-11 14:56 被阅读0次

    题目描述

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

    例如:
    给定二叉树 [3,9,20,null,null,15,7],

        3
       / \
      9  20
        /  \
       15   7
    

    返回其自底向上的层次遍历为:

    [
      [15,7],
      [9,20],
      [3]
    ]
    
    知识点

    二叉树、层次遍历


    Qiang的思路

    # Definition for a binary tree node.
    # class TreeNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.left = None
    #         self.right = None
    
    class Solution:
        def levelOrderBottom(self, root: TreeNode) -> List[List[int]]:
            if root==None:
                return []
            list=[root,'#']
            result=[]
            cur=[]
            while list!=['#']:
                c=list[0]
                list.pop(0)
                if c=='#':
                    list.append('#')
                    result.insert(0,cur)
                    cur=[]
                else:
                    list.append(c.left) if c.left!=None else None
                    list.append(c.right) if c.right!=None else None
                    cur.append(c.val)
            result.insert(0,cur)
            return result
    

    作者原创,如需转载及其他问题请邮箱联系:lwqiang_chn@163.com
    个人网站:https://www.myqiang.top

    相关文章

      网友评论

        本文标题:107. 二叉树的层次遍历 II

        本文链接:https://www.haomeiwen.com/subject/szcbpqtx.html