Convert Binary Tree to Linked Lists by Depth

update Sep 14,2017 20:47

LeetCodearrow-up-right

Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you'll have D linked lists).

Example

  Given binary tree:

    1
   / \
  2   3
 /
4
return

[
  1->null,
  2->3->null,
  4->null
]

Basic Idea:

基本框架是一个BFS分层遍历,每层在开始 poll 之前都要定义好一个 dummy list node 作为head节点,然后开始本层遍历,每个node的值加到 dummy 后面,每层结束后,该层的 head 就是 dummy.next;

Python Code:

update Dec 29, 2017 1:09

Update

更新一个 Java solution,和之前一样的方法,分层BFS;