题解 | #基本字符串压缩#
输出单层结点
http://www.nowcoder.com/practice/cb6c883b123b44399377d0c71e6ba3ea
bfs的变形
用count保存当前层数,当达到dep时进行成殓操作
public class TreeLevel { public ListNode getTreeLevel(TreeNode root, int dep) { // write code here int count = 1; Deque<TreeNode> queue = new ArrayDeque<>(); queue.offer(root); ListNode head = new ListNode(-1); ListNode p = head; while(!queue.isEmpty()){ for(int i = queue.size() - 1; i >= 0 ; i --){ TreeNode node = queue.poll(); if(count == dep){ p.next = new ListNode(node.val); p = p.next; } if(node.left != null) queue.add(node.left); if(node.right != null) queue.add(node.right); } count ++; } return head.next; } }