Skip to content

Instantly share code, notes, and snippets.

@XDo0
Last active October 30, 2022 16:10
Show Gist options
  • Save XDo0/27b7d4f0a61ec9cad8a7484a501ecce9 to your computer and use it in GitHub Desktop.
Save XDo0/27b7d4f0a61ec9cad8a7484a501ecce9 to your computer and use it in GitHub Desktop.
binary tree level order
// 102.二叉树的层序遍历
class Solution {
public List<List<Integer>> resList = new ArrayList<List<Integer>>();
public List<List<Integer>> levelOrder(TreeNode root) {
//checkFun01(root,0);
checkFun02(root);
return resList;
}
//DFS--递归方式
public void checkFun01(TreeNode node, Integer deep) {
if (node == null) return;
deep++;
if (resList.size() < deep) {
//当层级增加时,list的Item也增加,利用list的索引值进行层级界定
List<Integer> item = new ArrayList<Integer>();
resList.add(item);
}
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>();
// len是将要访问层的节点长度
int len = que.size();
// 因为二叉树只会向下访问节点,不必维护visited
while (len > 0) {
TreeNode tmpNode = que.poll();
// 可以在出栈加入itemList
itemList.add(tmpNode.val);
// 当前访问点的子节点
if (tmpNode.left != null) que.offer(tmpNode.left);
// 也可以遍历到的时候加入itemList
// 即itemList.add(tmpNode.left)
if (tmpNode.right != null) que.offer(tmpNode.right);
len--;
}
// 循环结束时当前层的节点都保存到itemList里了
resList.add(itemList);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment