mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 02:53:31 +08:00
优化 0102.二叉树的层序遍历.md Java版本(增加迭代方式)
This commit is contained in:
@ -419,18 +419,17 @@ public:
|
||||
|
||||
Java:
|
||||
|
||||
``` Java
|
||||
|
||||
|
||||
```Java
|
||||
class Solution {
|
||||
public List<List<Integer>> resList=new ArrayList<List<Integer>>();
|
||||
public List<List<Integer>> 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<TreeNode> que=new LinkedList<TreeNode>();
|
||||
que.offer(node);
|
||||
|
||||
while(!que.isEmpty()){
|
||||
List<Integer> itemList=new ArrayList<Integer>();
|
||||
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)
|
||||
|
Reference in New Issue
Block a user