欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java实现广度优先搜索(BFS)深度优先搜索(DFS)

程序员文章站 2022-06-11 12:25:19
...

如何用java实现对二叉树的DFS和BFS?

首先,一个简单二叉树如下图:
java实现广度优先搜索(BFS)深度优先搜索(DFS)

每一个结点的数据域为整型,有左节点和右节点

实现如下

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * @author WangMingMing
 * @creat 2020-04-10 7:58
 */
public class BinaryTreeSearch {
    public static void main(String[] args) {
        //创建二叉树
        TreeNode treeNode4 = new TreeNode(4);
        TreeNode treeNode5 = new TreeNode(5);
        TreeNode treeNode2 = new TreeNode(treeNode4, treeNode5, 2);
        TreeNode treeNode6 = new TreeNode(6);
        TreeNode treeNode7 = new TreeNode(7);
        TreeNode treeNode3 = new TreeNode(treeNode6, treeNode7, 3);
        TreeNode treeNode1 = new TreeNode(treeNode2, treeNode3, 1);

        //对深度优先搜索进行测试:
        System.out.println("对深度优先搜索进行测试结果如下: ");
        depthFirstSearch(treeNode1);
        System.out.println();

        //对广度优先搜索进行测试:
        System.out.println("对广度优先搜索进行测试结果如下: ");
        broadFirstSearch(treeNode1);
        System.out.println();
    }



    //深度优先搜索
    public static void depthFirstSearch(TreeNode root){
        if(root == null){
            return ;
        }
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode temp = stack.pop();
            System.out.print(temp.data + "  ");
            if(temp.rightNode != null){
                stack.push(temp.rightNode);
            }
            if(temp.leftNode != null){
                stack.push(temp.leftNode);
            }
        }
    }

    //广度优先搜索
    public static void broadFirstSearch(TreeNode root){
        if(root == null){
            return ;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode temp = queue.poll();
            System.out.print(temp.data + "  ");
            if(temp.leftNode != null){
                queue.add(temp.leftNode);
            }
            if(temp.rightNode != null){
                queue.add(temp.rightNode);
            }
        }
    }



}


/**
 * data为数据域
 * 左右两个结点
 */
class TreeNode{
    int data;
    TreeNode leftNode;
    TreeNode rightNode;
    public TreeNode(){

    }
    public TreeNode(int data){
        this.data = data;
    }

    public TreeNode(TreeNode leftNode, TreeNode rightNode, int data){
        this.leftNode = leftNode;
        this.rightNode = rightNode;
        this.data = data;
    }
}

测试结果如下
java实现广度优先搜索(BFS)深度优先搜索(DFS)