题解 | #顺时针打印矩阵#

从上往下打印二叉树

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]
current_layer=-1
list_val=[]
list_layer=[]
def PrintFromTopToBottom(self, root):
# write code here
self.FromTopToBottom(root)
if len(self.list_val)!=0:
return self.cal_ans(self.list_val,self.list_layer)
else:
return None
def FromTopToBottom(self, root):
self.current_layer+=1
if root==None:
self.current_layer-=1
return None
else:
self.list_val.append(root.val)
self.list_layer.append(self.current_layer)
self.FromTopToBottom(root.left)
self.FromTopToBottom(root.right)
self.current_layer-=1
return
#return self.cal_ans(self.list_val,self.list_layer)
def cal_ans(self,list_val,list_layer):
layer_num=max(list_layer)+1
ans=[]
for i in range(layer_num):
ans.append([])
for i in range(len(list_val)):
ans[list_layer[i]].append(list_val[i])
output=[]
for i in range(layer_num):
output=output+ans[i]
return output

全部评论

相关推荐

06-26 15:35
武汉大学 运营
点赞 评论 收藏
分享
06-26 10:08
门头沟学院 C++
北京Golang实习,一个月4700,吃住都不报,公司位置在海淀。请问友友怎么看呢?如果要租房的话有什么建议吗
码农索隆:租房肯定是合租了,剩下的钱,差不多够正常吃饭了,看看能不能学到东西吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务