Performing Breadth First Search recursively

后端 未结 21 2604
不思量自难忘°
不思量自难忘° 2020-11-28 01:12

Let\'s say you wanted to implement a breadth-first search of a binary tree recursively. How would you go about it?

Is it possible using only the call-stack

21条回答
  •  时光说笑
    2020-11-28 01:56

    A simple BFS and DFS recursion in Java:
    Just push/offer the root node of the tree in the stack/queue and call these functions.

    public static void breadthFirstSearch(Queue queue) {
    
        if (queue.isEmpty())
            return;
    
        Node node = (Node) queue.poll();
    
        System.out.println(node + " ");
    
        if (node.right != null)
            queue.offer(node.right);
    
        if (node.left != null)
            queue.offer(node.left);
    
        breadthFirstSearch(queue);
    }
    
    public static void depthFirstSearch(Stack stack) {
    
        if (stack.isEmpty())
            return;
    
        Node node = (Node) stack.pop();
    
        System.out.println(node + " ");
    
        if (node.right != null)
            stack.push(node.right);
    
        if (node.left != null)
            stack.push(node.left);
    
        depthFirstSearch(stack);
    }
    

提交回复
热议问题