二叉树层序遍历,使用队列

    xiaoxiao2022-07-12  135

    参考:程序员小灰

     

    package chapter3.part2; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import org.junit.Test; public class BinaryTreeFindWithQueue { @Test public void levelPrintBinaryTree() { LinkedList<Integer> inputList = new LinkedList<Integer>(Arrays. asList(new Integer[] {3,2,9,null,null,10,null,null,8,null,4})); TreeNode root = createBinary(inputList); System.out.println("二叉树层序遍历:"); printBinaryTreeWithQueue(root); } private void printBinaryTreeWithQueue(TreeNode root) { Queue<TreeNode> queue = new LinkedList<TreeNode>();//通过LinkedList创建队列 queue.offer(root); while(!queue.isEmpty()) { TreeNode node = queue.poll(); System.out.println(node.data); //甩掉本元素时,让自己的左右孩子入队列,追加到队尾 if(node.leftNode != null) { queue.offer(node.leftNode); } if(node.rightNode != null) { queue.offer(node.rightNode); } } } private TreeNode createBinary(LinkedList<Integer> inputList) { TreeNode node = null; if(inputList == null || inputList.isEmpty()) { return null; } Integer data = inputList.removeFirst(); if(data != null) { node = new TreeNode(data); node.leftNode = createBinary(inputList); node.rightNode = createBinary(inputList); } return node; } }

     

    注意:       要通过LinkedList创建队列

     Queue<TreeNode> queue = new LinkedList<TreeNode>();


    走过了人来人往

    不喜欢也得欣赏

    我是沉默的存在~

    最新回复(0)