Python把二叉树打印成多行

本文阅读 1 分钟
首页 Python笔记 正文

引入两个队列。首先把当前层的节点存入到一个队列queue1中,然后遍历当前队列queue1,在遍历的过程中,如果节点有左子树或右子树,依次存入另一个队列queue2。然后遍历队列queue2,如此往复。

  1. '''
  2. 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
  3. '''
  4. # -*- coding:utf-8 -*-
  5. class TreeNode:
  6. def __init__(self, x):
  7. self.val = x
  8. self.left = None
  9. self.right = None
  10. class Solution:
  11. # 返回二维列表[[1,2],[4,5]]
  12. def levelOrder(self, pRoot):
  13. if pRoot == None:
  14. return []
  15. nodes, res = [pRoot], []
  16. while nodes:
  17. curStack, nextStack = [], []
  18. for node in nodes:
  19. curStack.append(node.val)
  20. if node.left:
  21. nextStack.append(node.left)
  22. if node.right:
  23. nextStack.append(node.right)
  24. res.append(curStack)
  25. nodes = nextStack
  26. return res
  27. pNode1 = TreeNode(8)
  28. pNode2 = TreeNode(6)
  29. pNode3 = TreeNode(10)
  30. pNode4 = TreeNode(5)
  31. pNode5 = TreeNode(7)
  32. pNode6 = TreeNode(9)
  33. pNode7 = TreeNode(11)
  34. pNode1.left = pNode2
  35. pNode1.right = pNode3
  36. pNode2.left = pNode4
  37. pNode2.right = pNode5
  38. pNode3.left = pNode6
  39. pNode3.right = pNode7
  40. S = Solution()
  41. aList = S.Print(pNode1)
  42. print(aList)
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

Python对称的二叉树
« 上一篇 01-21
Python按之字形顺序打印二叉树
下一篇 » 01-21

发表评论

惪特博客
  • 文章总数:
    18501 篇
  • 评论总数:
    53360 条
  • 标签总数:
    8881 个
  • 总浏览量:
    23364117 次
  • 最后更新:
    6天前

最多点赞

随便看看

标签TAG