Python:把二叉樹列印成多行
阿新 • • 發佈:2019-01-07
牛客網上的劍指 offer的線上程式設計:
題目描述
從上到下按層列印二叉樹,同一層結點從左至右輸出。每一層輸出一行。# -*- 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 Print(self, pRoot): # write code here if not pRoot: return [] res, tree = [], [pRoot] while tree: row, sub_tree = [], [] for item in tree: row.append(item.val) if item.left: sub_tree.append(item.left) if item.right: sub_tree.append(item.right) res.append(row) tree = sub_tree return res