Python实现"二叉树的层次遍历||"的一种方法

给定一棵二叉树,返回从上到下按层级顺序遍历结点的值(例如,从叶子节点的层级到根结点的层级)

例如:

二叉树[3,9,20,null,null,15,7],

   3
   / \
  9  20
    /  \
   15   7

返回它从下到上按层级顺序遍历的结果为:

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

1:从上到下按层级遍历二叉树

def levelOrderBottom(self, root):
        """
        :type root: TreeNode
        :rtype: List[List[int]]
        """
        if not root:       #树为空
            return []
        curList = [root]   #存放从上到下,当前层级的树结点
        rList = []         #存放返回的整数值列表
        while curList:     #从上到下遍历树
            tempNodeList = []    #存放下层的结点
            tempValList = []     #存放当前层级的数值
            for node in curList:  #遍历当前层级的结点
                tempValList.append(node.val)   #添加结点值
                if node.left is not None:      
                    tempNodeList.append(node.left)
                if node.right is not None:
                    tempNodeList.append(node.right)
            curList = tempNodeList     
            rList.append(tempValList)   #当前层级数值列表压入总列表中
        return rList[::-1]   #反序输出

算法题来自:https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82352827