DFS(深度优先搜索)和 BFS(广度优先搜索)
DFS遍历使用的是递归(递归使用了系统中栈的数据结构)
void dfsTraversal(TreeNode root) {
if (root == null) {
return;
}
dfsTraversal(root.left);
dfsTraversal(root.right);
}
BFS遍历使用队列的数据结构
Traversal
void bfsTraversal(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll(); // cur = 弹出队列的节点 需要画图理解
if (cur.left != null) { //左树不为空时,左树节点加入队列
queue.offer(cur.left);
}
if (cur.right != null) { //右树不为空时,右树节点加入队列
queue.offer(cur.right);
}
}
}
DFS与BFS遍历方式的不同
DFS是依靠递归来进行移动遍历的
BFS是依靠类似于指针来进行移动的,与链表的遍历相似,先把一个树节点root加入队列offer(root),然后再弹出队列,cur接收弹出队列的值,然后cur就可以通过cur.left和cur.right来进行移动了。
下面做一道层序遍历的OJ题
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。 (即逐层地,从左到右访问所有节点)。
示例:
二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层序遍历结果:
[
[3],
[9,20],
[15,7]
]
需求:
用二维数组进行层序遍历
做法:
List<List<Integer>> //意思是列表中存储的是包含数字的列表
先写上层序遍历的代码,再在层序遍历的基础上达到需求
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
TreeNode cur = queue.poll();
if(cur.left != null){
queue.offer(cur.left);
}
if(cur.right != null){
queue.offer(cur.right);
}
}
}
}
题目的意思是要一个二维数组去储存每一层的数组
ret[0] list[3]
ret[1] list[9,20]
ret[2] list[15,7]
接下来就新建一个二维数组即可
先新建ret数组,因为ret数组里储存的也是数组,所以还需要在ret中新建一个数组
List<List<Integer>> ret = new ArrayList<>();
if(root == null) return ret;
求出队列里的元素个数size,再用size次出队,加入到数组list中
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ret = new ArrayList<>();
if(root == null) return ret;
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size(); // 求出队列的长度
List<Integer> list = new ArrayList<>(); //新建一个数组list
while (size != 0) {
TreeNode cur = queue.poll(); //用cur接收出队的节点
list.add(cur.val); //节点的val值加入到list数组中
size--;
if(cur.left!=null) {
queue.offer(cur.left);
}
if(cur.right != null) {
queue.offer(cur.right); //把左树和右树加入到队列中
}
}
ret.add(list); //把list加入到数组ret中
}
return ret;
}
}
import java.util.*;
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null) {
return new ArrayList<List<Integer>>();
}
List<List<Integer>> res = new ArrayList<List<Integer>>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
//将根节点放入队列中,然后不断遍历队列
queue.add(root);
while(queue.size()>0) {
//获取当前队列的长度,这个长度相当于 当前这一层的节点个数
int size = queue.size();
ArrayList<Integer> tmp = new ArrayList<Integer>();
//将队列中的元素都拿出来(也就是获取这一层的节点),放到临时list中
//如果节点的左/右子树不为空,也放入队列中
for(int i=0;i<size;++i) {
TreeNode t = queue.remove();
tmp.add(t.val);
if(t.left!=null) {
queue.add(t.left);
}
if(t.right!=null) {
queue.add(t.right);
}
}
//将临时list加入最终返回结果中
res.add(tmp);
}
return res;
}
}
作者:wang_ni_ma
链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal/solution/die-dai-di-gui-duo-tu-yan-shi-102er-cha-shu-de-cen/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。