How do implement a breadth first traversal?

前端 未结 9 1334
萌比男神i
萌比男神i 2020-11-28 21:34

This is what I have. I thought pre-order was the same and mixed it up with depth first!

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

public class Ex         


        
相关标签:
9条回答
  • 2020-11-28 22:19
    public void breadthFirstSearch(Node root, Consumer<String> c) {
        List<Node> queue = new LinkedList<>();
    
        queue.add(root);
    
        while (!queue.isEmpty()) {
            Node n = queue.remove(0);
            c.accept(n.value);
    
            if (n.left != null)
                queue.add(n.left);
            if (n.right != null)
                queue.add(n.right);
        }
    }
    

    And the Node:

    public static class Node {
        String value;
        Node left;
        Node right;
    
        public Node(final String value, final Node left, final Node right) {
            this.value = value;
            this.left = left;
            this.right = right;
        }
    }
    
    0 讨论(0)
  • 2020-11-28 22:22

    Breadth first search

    Queue<TreeNode> queue = new LinkedList<BinaryTree.TreeNode>() ;
    public void breadth(TreeNode root) {
        if (root == null)
            return;
        queue.clear();
        queue.add(root);
        while(!queue.isEmpty()){
            TreeNode node = queue.remove();
            System.out.print(node.element + " ");
            if(node.left != null) queue.add(node.left);
            if(node.right != null) queue.add(node.right);
        }
    
    }
    
    0 讨论(0)
  • 2020-11-28 22:22

    Use the following algorithm to traverse in breadth first search-

    1. First add the root node into the queue with the put method.
    2. Iterate while the queue is not empty.
    3. Get the first node in the queue, and then print its value.
    4. Add both left and right children into the queue (if the current nodehas children).
    5. Done. We will print the value of each node, level by level,by poping/removing the element

    Code is written below-

        Queue<TreeNode> queue= new LinkedList<>();
        private void breadthWiseTraversal(TreeNode root) {
            if(root==null){
                return;
            }
            TreeNode temp = root;
            queue.clear();
            ((LinkedList<TreeNode>) queue).add(temp);
            while(!queue.isEmpty()){
                TreeNode ref= queue.remove();
                System.out.print(ref.data+" ");
                if(ref.left!=null) {
                    ((LinkedList<TreeNode>) queue).add(ref.left);
                }
                if(ref.right!=null) {
                    ((LinkedList<TreeNode>) queue).add(ref.right);
                }
            }
        }
    
    0 讨论(0)
提交回复
热议问题