1. 程式人生 > >劍指Offer 60. 把二叉樹列印成多行 (二叉樹)

劍指Offer 60. 把二叉樹列印成多行 (二叉樹)

題目描述

從上到下按層列印二叉樹,同一層結點從左至右輸出。每一層輸出一行。

題目地址

https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&rp=3&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

思路

比上題簡單,直接層次遍歷

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)