From 9fa21a5e8fab1073c4421189f5a0703ff1b653b2 Mon Sep 17 00:00:00 2001 From: doo0301 Date: Wed, 12 May 2021 19:56:58 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=200102.=E4=BA=8C=E5=8F=89?= =?UTF-8?q?=E6=A0=91=E7=9A=84=E5=B1=82=E5=BA=8F=E9=81=8D=E5=8E=86.md=20Jav?= =?UTF-8?q?a=E7=89=88=E6=9C=AC=EF=BC=88=E5=A2=9E=E5=8A=A0=E8=BF=AD?= =?UTF-8?q?=E4=BB=A3=E6=96=B9=E5=BC=8F=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0102.二叉树的层序遍历.md | 35 +++++++++++++++++------ 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/problems/0102.二叉树的层序遍历.md b/problems/0102.二叉树的层序遍历.md index be2e9dca..0781e01d 100644 --- a/problems/0102.二叉树的层序遍历.md +++ b/problems/0102.二叉树的层序遍历.md @@ -419,18 +419,17 @@ public: Java: -``` Java - - +```Java class Solution { public List> resList=new ArrayList>(); public List> levelOrder(TreeNode root) { - checkFun01(root,0); - + //checkFun01(root,0); + checkFun02(root); + return resList; } - //递归方式 + //DFS--递归方式 public void checkFun01(TreeNode node,Integer deep){ if(node==null) return; deep++; @@ -442,12 +441,33 @@ class Solution { } resList.get(deep-1).add(node.val); - checkFun01(node.left,deep); checkFun01(node.right,deep); } + + //BFS--迭代方式--借助队列 + public void checkFun02(TreeNode node){ + if(node==null) return; + Queue que=new LinkedList(); + que.offer(node); + while(!que.isEmpty()){ + List itemList=new ArrayList(); + int len=que.size(); + while(len>0){ + TreeNode tmpNode=que.poll(); + itemList.add(tmpNode.val); + + if(tmpNode.left!=null) que.offer(tmpNode.left); + if(tmpNode.right!=null) que.offer(tmpNode.right); + len--; + } + + resList.add(itemList); + } + + } ``` @@ -458,7 +478,6 @@ Go: - ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw) * B站视频:[代码随想录](https://space.bilibili.com/525438321)