Python从上往下打印二叉树

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

引入一个队列即可。

  1. '''
  2. 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
  3. '''
  4. '''
  5. 相当于按层遍历, 中间需要队列做转存
  6. '''
  7. # -*- coding:utf-8 -*-
  8. class TreeNode:
  9. def __init__(self, x):
  10. self.val = x
  11. self.left = None
  12. self.right = None
  13. class Solution:
  14. # 返回从上到下每个节点值列表,例:[1,2,3]
  15. def PrintFromTopToBottom(self, root):
  16. queue = []
  17. if not root:
  18. return []
  19. result = []
  20. queue.append(root)
  21. while len(queue) > 0:
  22. currentRoot = queue.pop(0)
  23. result.append(currentRoot.val)
  24. if currentRoot.left:
  25. queue.append(currentRoot.left)
  26. if currentRoot.right:
  27. queue.append(currentRoot.right)
  28. return result
  29. pNode1 = TreeNode(8)
  30. pNode2 = TreeNode(6)
  31. pNode3 = TreeNode(10)
  32. pNode4 = TreeNode(5)
  33. pNode5 = TreeNode(7)
  34. pNode6 = TreeNode(9)
  35. pNode7 = TreeNode(11)
  36. pNode1.left = pNode2
  37. pNode1.right = pNode3
  38. pNode2.left = pNode4
  39. pNode2.right = pNode5
  40. pNode3.left = pNode6
  41. pNode3.right = pNode7
  42. S = Solution()
  43. print(S.PrintFromTopToBottom(pNode1))
解压密码: detechn或detechn.com

免责声明

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

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

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

Python栈的压入、弹出序列
« 上一篇 01-21
Python二叉搜索树的后续遍历序列
下一篇 » 01-21

发表评论