输出单层节点
输出单层结点
http://www.nowcoder.com/questionTerminal/cb6c883b123b44399377d0c71e6ba3ea
层次遍历应用
import java.util.*; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } }*/ public class TreeLevel { public ListNode getTreeLevel(TreeNode root, int dep) { // write code here LinkedList<TreeNode> q = new LinkedList<>(); q.offer(root); ListNode head = new ListNode(0); ListNode cur = head; int count = 0; while( !q.isEmpty()){ int size = q.size(); count++; for(int i = 0; i< size;++i){ root = q.poll(); if(count == dep){ cur.next = new ListNode(root.val); cur = cur.next; } if(root.left != null){ q.offer(root.left); } if(root.right != null){ q.offer(root.right); } } } return head.next; } }