广度优先搜索--二叉树按层遍历
Posted moris5013
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了广度优先搜索--二叉树按层遍历相关的知识,希望对你有一定的参考价值。
二叉树按层遍历
public class WideFirstSearch { public static void main(String[] args) { Node root = new Node("A"); root.left = new Node("B"); root.right = new Node("C"); root.left.left = new Node("D"); root.left.right = new Node("E"); root.left.right.left = new Node("G"); root.right.right = new Node("F"); List<List<String>> res = wfs(root); for(int i = 0 ; i<res.size() ; i++) { System.out.print("第"+(i+1)+"层: "); res.get(i).forEach(x -> System.out.print(x + " ")); System.out.println(); } } public static List<List<String>> wfs(Node root){ List<List<String>> res = new ArrayList<List<String>>(); LinkedList<Node> queue = new LinkedList<Node>(); queue.addLast(root); while(!queue.isEmpty()) { int size = queue.size(); List<String> list = new ArrayList<>(); while(size>0) { Node temp = queue.pollFirst(); list.add(temp.value); if(temp.left != null) { queue.addLast(temp.left ); } if(temp.right != null) { queue.addLast(temp.right); } size --; } res.add(list); } return res; } } class Node{ String value; Node left; Node right; Node(String value){ this.value = value; } }
以上是关于广度优先搜索--二叉树按层遍历的主要内容,如果未能解决你的问题,请参考以下文章