描述 从上往下打印出二叉树的每个节点,同层节点从左至右打印。示例1 输入:{5,4,,3,,2,,1} 返回值:〔5,4,3,2,1〕 第一种解法,使用一个队列来做完辅助工具,由于队列的特性的先进先出,第一次就把根节点放进去,然后循环遍历左右节点,依次放入队列中,最后依次从队列中取出节点,放入list中即可,代码如下publicstaticArrayListIntegerfirstPrintFromTopToBottom(TreeNodeIntegerroot){ArrayListIntegerlistnewArrayList();if(nullroot){returnlist;}QueueTreeNodequeuenewLinkedList();queue。offer(root);while(!queue。isEmpty()){TreeNodeIntegerpollqueue。poll();list。add(poll。val);if(null!poll。left){queue。offer(poll。left);}if(null!poll。right){queue。offer(poll。right);}}returnlist;} 第二种解法,先计算出树的最大深度,然后依次循环遍历即可,代码如下publicstaticArrayListIntegersecondPrintFromTopToBottom(TreeNodeIntegerroot){ArrayListIntegerlistnewArrayList();if(nullroot){returnlist;}intdepthdepth(root);for(inti0;idepth;i){foreachTree(root,i,list);}returnlist;}publicstaticvoidforeachTree(TreeNodeIntegerroot,intlevel,ArrayListIntegerlist){if(nullroot){return;}if(level0){list。add(root。val);}foreachTree(root。left,level1,list);foreachTree(root。right,level1,list);}求树的最大深度paramrootreturnpublicstaticintdepth(TreeNoderoot){if(nullroot){return0;}intldepth(root。left);intrdepth(root。right);if(lr){returnl1;}else{returnr1;}} 完整代码如下publicclassMainPrintFromTopToBottom{publicstaticvoidmain(String〔〕args){根节点10TreeNodetreeNode1newTreeNode(10);左孩子9TreeNodetreeNode2newTreeNode(9);右孩子20TreeNodetreeNode3newTreeNode(20);20的左孩子15TreeNodetreeNode4newTreeNode(15);20的右孩子35TreeNodetreeNode5newTreeNode(35);根节点的左右孩子treeNode1。setLeft(treeNode2);treeNode1。setRight(treeNode3);20节点的左右孩子treeNode3。setLeft(treeNode4);treeNode3。setRight(treeNode5);ArrayListIntegerintegerssecondPrintFromTopToBottom(treeNode1);System。out。println(integersintegers);}publicstaticArrayListIntegerfirstPrintFromTopToBottom(TreeNodeIntegerroot){ArrayListIntegerlistnewArrayList();if(nullroot){returnlist;}QueueTreeNodequeuenewLinkedList();queue。offer(root);while(!queue。isEmpty()){TreeNodeIntegerpollqueue。poll();list。add(poll。val);if(null!poll。left){queue。offer(poll。left);}if(null!poll。right){queue。offer(poll。right);}}returnlist;}publicstaticArrayListIntegersecondPrintFromTopToBottom(TreeNodeIntegerroot){ArrayListIntegerlistnewArrayList();if(nullroot){returnlist;}intdepthdepth(root);for(inti0;idepth;i){foreachTree(root,i,list);}returnlist;}publicstaticvoidforeachTree(TreeNodeIntegerroot,intlevel,ArrayListIntegerlist){if(nullroot){return;}if(level0){list。add(root。val);}foreachTree(root。left,level1,list);foreachTree(root。right,level1,list);}求树的最大深度paramrootreturnpublicstaticintdepth(TreeNoderoot){if(nullroot){return0;}intldepth(root。left);intrdepth(root。right);if(lr){returnl1;}else{returnr1;}}}