Welcome 微信登录

首页 / 操作系统 / Linux / 把二叉树打印成多行(二叉树的层次遍历)

题目描述从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。二叉树的层次遍历,对于每一层的元素放在同一个列表中即可# -*- coding:utf-8 -*-
# class TreeNode:
#   def __init__(self, x):
#       self.val = x
#       self.left = None
#       self.right = None
class Solution:
    # 返回二维列表[[1,2],[4,5]]
    def Print(self, pRoot):
        # write code here
        if pRoot is None:
         return []
        p = [pRoot]
        res = []
        while p:
         node = []
         li = []         for x in p:
          if x.left:
           node.append(x.left)
          if x.right:
           node.append(x.right)
          li.append(x.val)
         p = node
         res.append(li)        return res求二叉树中两个节点的最远距离 http://www.linuxidc.com/Linux/2016-08/134049.htm根据二叉树的前序数组和中序序遍历数组生成二叉树 http://www.linuxidc.com/Linux/2016-09/135514.htm判断一个二叉树是否是平衡二叉树 http://www.linuxidc.com/Linux/2016-07/132842.htm轻松搞定面试中的二叉树题目 http://www.linuxidc.com/linux/2014-07/104857.htm二叉树的先序、中序、后序遍历 http://www.linuxidc.com/Linux/2016-06/132504.htm本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-01/140040.htm