List of Depths: 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).
publicList<List>depthLists(Noderoot){List<List>depthLists=newArrayList<>();ListnextLevel=newArrayList<>();nextLevel.add(root);while(!nextLevel.isEmpty()){depthLists.add(nextLevel);Listcurrent=nextLevel;// current levelnextLevel=newList();// prepare for next levelfor(Noden:current){if(n.left!=null){nextLevel.add(n.left);}if(n.right!=null){nextLevel.add(n.right);}}}returndepthLists;}
评论