把二叉树打印成多行(二叉树的层次遍历)

题目描述

从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

二叉树的层次遍历,对于每一层的元素放在同一个列表中即可

# -*- 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

猜你喜欢

转载自www.linuxidc.com/Linux/2017-01/140040.htm