1. 程式人生 > >2017-12-11

2017-12-11

src pty val nodes list isempty poll create emp

242. Convert Binary Tree to Linked Lists by Depth

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).

*dummy node的使用,中間node和dummy node的關系。

技術分享圖片
 1 /**
 2  * Definition of TreeNode:
 3  * public class TreeNode {
4 * public int val; 5 * public TreeNode left, right; 6 * public TreeNode(int val) { 7 * this.val = val; 8 * this.left = this.right = null; 9 * } 10 * } 11 * Definition for singly-linked list. 12 * public class ListNode { 13 * int val; 14 * ListNode next;
15 * ListNode(int x) { val = x; } 16 * } 17 */ 18 public class Solution { 19 /** 20 * @param root the root of binary tree 21 * @return a lists of linked list 22 */ 23 public List<ListNode> binaryTreeToLists(TreeNode root) { 24 // Write your code here 25 List<ListNode> res = new
ArrayList<>(); 26 if (root == null) { 27 return res; 28 } 29 Queue<TreeNode> queue = new LinkedList<>(); 30 queue.add(root); 31 ListNode head = new ListNode(0); 32 while (!queue.isEmpty()) { 33 int size = queue.size(); 34 ListNode ln = head; 35 for (int i = 0; i < size; i++) { 36 TreeNode node = queue.poll(); 37 ln.next = new ListNode(node.val); 38 ln = ln.next; 39 if (node.left != null) { 40 queue.add(node.left); 41 } 42 if (node.right != null) { 43 queue.add(node.right); 44 } 45 } 46 res.add(head.next); 47 } 48 return res; 49 } 50 }
View Code

2017-12-11