Python把二叉树打印成多行
引入两个队列。首先把当前层的节点存入到一个队列queue1中,然后遍历当前队列queue1,在遍历的过程中,如果节点有左子树或右子树,依次存入另一个队列queue2。然后遍历队列queue2,如此往复。
- '''
- 从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
- '''
-
- # -*- 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 levelOrder(self, pRoot):
- if pRoot == None:
- return []
- nodes, res = [pRoot], []
- while nodes:
- curStack, nextStack = [], []
- for node in nodes:
- curStack.append(node.val)
- if node.left:
- nextStack.append(node.left)
- if node.right:
- nextStack.append(node.right)
- res.append(curStack)
- nodes = nextStack
- return res
-
-
- pNode1 = TreeNode(8)
- pNode2 = TreeNode(6)
- pNode3 = TreeNode(10)
- pNode4 = TreeNode(5)
- pNode5 = TreeNode(7)
- pNode6 = TreeNode(9)
- pNode7 = TreeNode(11)
-
- pNode1.left = pNode2
- pNode1.right = pNode3
- pNode2.left = pNode4
- pNode2.right = pNode5
- pNode3.left = pNode6
- pNode3.right = pNode7
-
- S = Solution()
- aList = S.Print(pNode1)
- print(aList)
解压密码: detechn或detechn.com
免责声明
本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。
本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。
本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。