我们今天研究下层次便利用BFS来实现
首先确定数据结构
/** * 二叉树数据结构节点 */ public class TreeNode { int value; TreeNode left; TreeNode right; public TreeNode(int val){ this.value = val; } }
然后走下场景的代码
import java.util.ArrayDeque; import java.util.ArrayList; import java.util.List; import java.util.Queue; public class BFSDemo { /*** * 层次遍历 * @param root * @return */ public List<List<Integer>> levelOrder(TreeNode root){ Queue<TreeNode> q = new ArrayDeque<>(); // 将根节点加入队列 if(null != root){ q.offer(root); } List<List<Integer>> res = new ArrayList<>(); while (!q.isEmpty()){ int sz = q.size(); // TODO 这里有优化空间 暂时不修改 List<Integer> num = new ArrayList<>(); for (int i = 0; i < sz; i++) { TreeNode cur = q.poll(); // 将左右节点加入队列 以备下一轮迭代 if(cur.left!=null){ q.offer(cur.left); } if(cur.right!=null){ q.offer(cur.right); } num.add(cur.value); } res.add(num); } return res; } public static void main(String[] args){ // 构建测试数据 TreeNode root = new TreeNode(9); TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node7 = new TreeNode(7); TreeNode node5 = new TreeNode(5); TreeNode node4 = new TreeNode(4); root.left = node1; root.right = node2; node2.left = node7; node2.right = node5; node7.left = node4; BFSDemo bfsDemo = new BFSDemo(); List<List<Integer>> list = bfsDemo.levelOrder(root); if(null==list){ return; } //System.out.println(list.toString()); for (int i = 0; i < list.size(); i++) { System.out.print("["); if(null !=list.get(i) && list.get(i).size()!=0) { for (int j = 0; j < list.get(i).size(); j++) { System.out.print( " "+list.get(i).get(j)+" "); } } System.out.println("]"); } } }
执行main run
结果
标签:TreeNode,cur,--,list,样例,int,new,Java,root From: https://www.cnblogs.com/zhou-789profession/p/17004636.html