给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。
示例:
输入:[1,2,3,4,5,null,7,8]
1
/
2 3
/
4 5 7
/
8
输出:[[1],[2,3],[4,5,7],[8]]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/list-of-depth-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def listOfDepth(self, root): """ :type tree: TreeNode :rtype: List[ListNode] """ if root is None: return [] res=[] #层次遍历 def add_to_res(level,node): if level>len(res)-1: res.append([]) res[level].append(node.val) if node.left: add_to_res(level+1,node.left) if node.right: add_to_res(level+1,node.right) add_to_res(0,root) def insert(root, item): temp = ListNode(item) #尾插法 if (root == None): root = temp else : ptr = root while (ptr.next != None): ptr = ptr.next ptr.next = temp return root #array转linked list def arrayToList(arr, n): root = None for i in range(0, n, 1): root = insert(root, arr[i]) return root ans=[] for arr in res: ans.append(arrayToList(list,len(arr))) return ans