题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
题目地址
思路
比上题简单,直接层次遍历
Python
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None node1 = TreeNode(1) node2 = TreeNode(2) node3 = TreeNode(3) node4 = TreeNode(4) node5 = TreeNode(5) node1.left = node2 node1.right = node3 node2.left = node4 node3.right = node5 class Solution: def Print(self, pRoot): # write code here ans = [] if not pRoot: return ans queue = [] queue.append(pRoot) while queue: temp = [] for i in range(len(queue)): r = queue.pop(0) temp.append(r.val) if r.left: queue.append(r.left) if r.right: queue.append(r.right) ans.append(temp) return ans if __name__ == '__main__': # [[1] [2 3] [4 5]] result = Solution().Print(node1) print(result)
作者:huangqiancun
出处:http://www.cnblogs.com/huangqiancun/
本博客若无特殊说明则由作者原创发布,欢迎转载,但请注明出处 :)