How do implement a breadth first traversal?

前端 未结 9 1338
萌比男神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: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 queue= new LinkedList<>();
        private void breadthWiseTraversal(TreeNode root) {
            if(root==null){
                return;
            }
            TreeNode temp = root;
            queue.clear();
            ((LinkedList) queue).add(temp);
            while(!queue.isEmpty()){
                TreeNode ref= queue.remove();
                System.out.print(ref.data+" ");
                if(ref.left!=null) {
                    ((LinkedList) queue).add(ref.left);
                }
                if(ref.right!=null) {
                    ((LinkedList) queue).add(ref.right);
                }
            }
        }
    

提交回复
热议问题