Python按之字形顺序打印二叉树

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

按之字形顺序打印二叉树需要两个栈。我们在打印某一行节点时,拔下一层的子节点保存到相应的栈里。如果当前打印的奇数层,则先保存左子节点再保存右子节点到第一个栈里;如果当前打印的是偶数层,则先保存右子节点再保存左子节点到第二个栈里。

  1. '''
  2. 请实现一个函数按照之字形打印二叉树,
  3. 即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
  4. '''
  5. # -*- coding:utf-8 -*-
  6. class TreeNode:
  7. def __init__(self, x):
  8. self.val = x
  9. self.left = None
  10. self.right = None
  11. class Solution:
  12. # 存储点的时候按照奇数层和偶数层分别存储
  13. def Print(self, pRoot):
  14. if not pRoot:
  15. return []
  16. result, nodes = [], [pRoot]
  17. right = True
  18. while nodes:
  19. curStack, nextStack = [], []
  20. if right:
  21. for node in nodes:
  22. curStack.append(node.val)
  23. if node.left:
  24. nextStack.append(node.left)
  25. if node.right:
  26. nextStack.append(node.right)
  27. else:
  28. for node in nodes:
  29. curStack.append(node.val)
  30. if node.right:
  31. nextStack.append(node.right)
  32. if node.left:
  33. nextStack.append(node.left)
  34. nextStack.reverse()
  35. right = not right
  36. result.append(curStack)
  37. nodes = nextStack
  38. return result
  39. # 转换思路,存储的时候一直从左向右存储,打印的时候根据不同的层一次打印
  40. def zigzagLevelOrder(self, root):
  41. if not root:
  42. return []
  43. levels, result, leftToRight = [root], [], True
  44. while levels:
  45. curValues, nextLevel = [], []
  46. for node in levels:
  47. curValues.append(node.val)
  48. if node.left:
  49. nextLevel.append(node.left)
  50. if node.right:
  51. nextLevel.append(node.right)
  52. if not leftToRight:
  53. curValues.reverse()
  54. if curValues:
  55. result.append(curValues)
  56. levels = nextLevel
  57. leftToRight = not leftToRight
  58. return result
  59. pNode1 = TreeNode(8)
  60. pNode2 = TreeNode(6)
  61. pNode3 = TreeNode(10)
  62. pNode4 = TreeNode(5)
  63. pNode5 = TreeNode(7)
  64. pNode6 = TreeNode(9)
  65. pNode7 = TreeNode(11)
  66. pNode1.left = pNode2
  67. pNode1.right = pNode3
  68. pNode2.left = pNode4
  69. pNode2.right = pNode5
  70. pNode3.left = pNode6
  71. pNode3.right = pNode7
  72. S = Solution()
  73. aList = S.Print(pNode1)
  74. print(aList)
解压密码: detechn或detechn.com

免责声明

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

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

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

Python把二叉树打印成多行
« 上一篇 01-21
Python序列化二叉树
下一篇 » 01-21

发表评论

惪特博客
  • 文章总数:
    18497 篇
  • 评论总数:
    53306 条
  • 标签总数:
    8873 个
  • 总浏览量:
    22596279 次
  • 最后更新:
    3天前

最多点赞

随便看看

标签TAG