DFS(深度优先遍历)和BFS(广度优先遍历)Java模板代码

前言

这次终于把深度优先-DFS和广度优先遍历-BFS弄明白了,用最基础的递归实现方式来记录一下。
先贴一下,二叉树基础节点代码TreeNode,以及N叉树的基础节点代码TreeNode2。

// 二叉树节点
public class TreeNode {
    /* 当前节点值 */
    int val;
    /* 左节点 */
    TreeNode left;
    /* 右节点 */
    TreeNode right;

    TreeNode(int val){
        this.val = val;
    }

    public int getVal() {
        return val;
    }

    public void setVal(int val) {
        this.val = val;
    }
}
// N叉树节点
public class TreeNode2 {
	/* 当前节点值 */
    public int val;
    /* 子节点 */
    public List<TreeNode2> children;

    public TreeNode2() {}

    public TreeNode2(int _val) {
        val = _val;
    }

    public TreeNode2(int _val, List<TreeNode2> _children) {
        val = _val;
        children = _children;
    }
}

深度优先遍历-DFS

在这里插入图片描述

static LinkedHashSet<Integer> visitedBinary = new LinkedHashSet<>();
// 二叉树深度优先遍历
public static void dfsBinary(TreeNode root){
    if(root == null || visitedBinary.contains(root.val)){
        return;
    }
    visitedBinary.add(root.val);
    dfsBinary(root.left);
    dfsBinary(root.right);
}
// N叉树深度优先遍历
public static void dfsChildren(TreeNode2 root,LinkedHashSet<Integer> visited){
    if(visited.contains(root.val)){
        return;
    }
    visited.add(root.val);
    if(root.children != null){
        for(TreeNode2 item : root.children){
            if(!visited.contains(item.val)){
                dfsChildren(item,visited);
            }
        }
    }
}

广度优先遍历-BFS

在这里插入图片描述

// 二叉树的广度遍历
public static List<Integer> bfsBinary(TreeNode root){

    List<Integer> resultList = new ArrayList<>();
    LinkedList<TreeNode> queue = new LinkedList<>();

    queue.add(root);

    while (!queue.isEmpty()){

        TreeNode node = queue.poll();
        resultList.add(node.val);
        if(node.left != null){
            queue.add(node.left);
        }
        if(node.right != null){
            queue.add(node.right);
        }
    }

    return resultList;
}
// N叉树广度优先遍历
public static List<Integer> bfsChildren(TreeNode2 root){

    List<Integer> resultList = new ArrayList<>();

    LinkedList<TreeNode2> queue = new LinkedList<>();

    queue.add(root);

    while (!queue.isEmpty()){

        TreeNode2 node = queue.poll();
        resultList.add(node.val);

        if(node.children != null && node.children.size()>0){
            for(int i=0;i<node.children.size();i++){
                queue.add(node.children.get(i));
            }
        }

    }
    return resultList;
}

层级遍历

贴完了广度优先遍历,再贴一下二叉树的层序遍历,其实二叉树的层序遍历和广度优先遍历还是有区别的,返回值是不一样的,BFS返回的是个一维数组,而层序遍历返回的是个二维数组,每层的数据都单独是一个数组。


```java
// 二叉树层序遍历
public static List<List<Integer>> layerBinary(TreeNode root){
    List<List<Integer>> result = new ArrayList<>();
    LinkedList<TreeNode> queue = new LinkedList();

    if(root !=null){
        queue.add(root);
    }
    while (!queue.isEmpty()){
        List<Integer> levelList = new ArrayList<>();
        // 记录每层元素数量
        int n = queue.size();
        for(int i=0;i<n;i++){
            TreeNode node = queue.poll();
            levelList.add(node.val);
            if(node.left != null){
                queue.add(node.left);
            }
            if(node.right != null){
                queue.add(node.right);
            }

        }
        // 每层遍历完成后,保存到最终数据结果中
        result.add(levelList);

    }
    return result;
}
// N叉树的层级遍历。
public static List<List<Integer>> layerEach(TreeNode2 root){

    List<List<Integer>> result = new ArrayList<>();
    LinkedList<TreeNode2> queue = new LinkedList();
    if(root != null){
        queue.add(root);
    }

    while (!queue.isEmpty()){
        List<Integer> levelList = new ArrayList<>();
        int n = queue.size();
        for(int i=0;i<n;i++){
            TreeNode2 node = queue.poll();
            levelList.add(node.val);
            if(node.children!=null){
                for(int j=0;j<node.children.size();j++){
                    queue.add(node.children.get(j));
                }
            }
        }
        result.add(levelList);
    }
    // 每层遍历完成后,保存到最终数据结果中
    return result;
}

测试用例

二叉树

public void binaryTest(){
    // 二叉树结构
    //             1
    //      2            5
    //   3     4       6   7

    // DFS-Binary
    dfsBinary(rootBinary);
    System.out.println("深度优先遍历(DFS)二叉树结果:"+JSON.toJSONString(visitedBinary));
    // BFS-Binary
    List<Integer> visitedBinaryList = bfsBinary(rootBinary);
    System.out.println("广度优先遍历(BFS)二叉树结果:"+JSON.toJSONString(visitedBinaryList));
    // 层级遍历-Binary
    List<List<Integer>> layerBinaryList = layerBinary(rootBinary);
    System.out.println("层级遍历二叉树结果:"+layerBinaryList);
}

运行结果:

深度优先遍历(DFS)二叉树结果:[1,2,3,4,5,6,7]
广度优先遍历(BFS)二叉树结果:[1,2,5,3,4,6,7]
层级遍历二叉树结果:[[1], [2, 5], [3, 4, 6, 7]]

N叉树

@Test
public void childrenTest(){
    //  N叉树结构
    //                   1
    //        2          5         9
    //    3           6     8           10
    //  4          7
    // DFS-N
    dfsChildren(root,visited);
    System.out.println("深度遍历(DFS)N叉树结果:"+ JSON.toJSONString(visited));
    // BFS-N
    List<Integer> bfsChildrenList = bfsChildren(root);
    System.out.println("广度遍历(BFS)N叉树结果:"+JSON.toJSONString(bfsChildrenList));
    // 层级遍历-N
    List<List<Integer>> layerEachList = layerEach(root);
    System.out.println("层级遍历N叉树结果:"+JSON.toJSONString(layerEachList));
}

运行结果:

深度遍历(DFS)N叉树结果:[1,2,3,4,5,6,7,8,9,10]
广度遍历(BFS)N叉树结果:[1,2,5,9,3,6,8,10,4,7]
层级遍历N叉树结果:[[1],[2,5,9],[3,6,8,10],[4,7]]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值