树的深度优先搜索和广度优先搜索的实现

1. 深度优先

depth first search,DFS
可以使用先序遍历来实现
递归版

//先序遍历
    public void PreOrder(BinaryTreeNode node){
        if(node!=null){
            System.out.println(node.getData()); //先访问根节点
            PreOrder(node.getLeftChild());  //先根遍历左子树
            PreOrder(node.getRightChild());  //先根遍历右子树
        }
    }

非递归版(使用栈实现)

 public ArrayList<Integer> DfsTree(TreeNode root) {
        ArrayList<Integer> lists = new ArrayList<I>();
        if(root == null)
            return lists;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while(!stack.isEmpty()){
            TreeNode tree = stack.pop();
      //先往栈中压入右节点,再压左节点,出栈就是先左节点后出右节点了(先序遍历推广)。
            if(tree.right != null)
                stack.push(tree.right);
            if(tree.left != null)
                stack.push(tree.left);
            lists.add(tree.val);
        }
        return lists;
    }

广度优先

BFS使用队列实现
广度优先搜索基本操作是和深度优先差不多的,只不过这里是通过队列来实现的,找到一个起点A,并将A相邻的点放入队列中,这时将队首元素B取出,并将B相邻且没有访问过的点放入队列中,不断重复这个操作,直至队列清空,这个时候依次访问的顶点就是遍历的顺序。
在这里插入图片描述
广度优先遍历树,需要用到队列(Queue)来存储节点对象,队列的特点就是先进先出。先往队列中插入左节点,再插入右节点,队列出队就是先出左节点,再出右节点。

首先将A节点插入队列中,队列中有元素(A);

将A节点弹出,同时将A节点的左节点B、右节点C依次插入队列,B在队首,C在队尾,(B,C),此时得到A节点;

将队首元素B弹出,并将B的左节点D、右节点E插入队列,C在队首,E在队尾(C,D,E),此时得到B节点;

再将队首元素C弹出,并将C节点的左节点F,右节点G依次插入队列,(D,E,F,G),此时得到C节点;

将D弹出,此时D没有子节点,队列中元素为(E,F,G),得到D节点;

。。。以此类推。最终的遍历结果为:A,B,C,D,E,F,G,H,I。

    public ArrayList<Integer> BfsTree(TreeNode root) {
        ArrayList<Integer> lists = new ArrayList<>();
        if(root == null)
            return lists;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode tree = queue.poll();
            if(tree.left != null)
                queue.offer(tree.left);
            if(tree.right != null)
                queue.offer(tree.right);
            lists.add(tree.val);
        }
        return lists;
    }
发布了76 篇原创文章 · 获赞 0 · 访问量 1998

猜你喜欢

转载自blog.csdn.net/weixin_43907800/article/details/104220757
今日推荐