题解 | #从上往下打印二叉树#
从上往下打印二叉树
http://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
-- coding:utf-8 --
class TreeNode:
def init(self, x):
self.val = x
self.left = None
self.right = None
class Solution: # 返回从上到下每个节点值列表,例:[1,2,3] def PrintFromTopToBottom(self, root): # write code here if not root: return
ret = []
curLevel = []
cur = root
curLevel.append(root)
while len(curLevel)>0:
nextLevel = []
for item in curLevel:
ret.append(item.val)
if item.left:
nextLevel.append(item.left)
if item.right:
nextLevel.append(item.right)
curLevel = nextLevel
return ret