赞
踩
二叉树分为广度遍历和深度遍历,在技术一面时遇到一个广度遍历的问题,题目如下:
给定义一个二叉树,树的结构如下:
需要遍历每一层节点的值,并输出如下结果:
[ [5],
[3, 7],
[2, 4, 6, 8],
[10, 11]
]
以前做的最多的都是深度遍历法,广度遍历有点懵懵的,后来想了下,就这样做了,什么也不说了直接上代码:
1. 节点定义
//节点的定义 public static class TreeNode { private int value; private TreeNode left = null; private TreeNode right = null; public TreeNode(int value, TreeNode left, TreeNode right) { this.value = value; this.left = left; this.right = right; } public TreeNode(int value){ this.value = value; } public void setLeftNode(TreeNode node) { this.left = node; } public void setRightNode(TreeNode node){ this.right = node; } public TreeNode getLeftNode(){ return this.left; } public TreeNode getRightNode(){ return this.right; } public int getData(){ return this.value; } }
2. 创建树
public static TreeNode createTree() { TreeNode firstLeft = new TreeNode(3); TreeNode firstRighe = new TreeNode(7); TreeNode root = new TreeNode(5, firstLeft, firstRighe); TreeNode leftSecondL = new TreeNode(2); TreeNode rightSecondL = new TreeNode(4); TreeNode leftSecondR = new TreeNode(6); TreeNode rightSecondR = new TreeNode(8); firstLeft.setLeftNode(leftSecondL); firstLeft.setRightNode(rightSecondL); firstRighe.setLeftNode(leftSecondR); firstRighe.setRightNode(rightSecondR); TreeNode leftThirdL = new TreeNode(10); TreeNode rightThirdL = new TreeNode(11); leftSecondL.setLeftNode(leftThirdL); leftSecondL.setRightNode(rightThirdL); return root; }
3、返回层级list
public static List<List<Integer>> treeList = new ArrayList<>(); public static void wideSerch(TreeNode root){ List<Integer> list=new ArrayList<Integer>(); //链表用来存储每一层数据 Queue<TreeNode> queue=new LinkedList<TreeNode>();//当前层队列 Queue<TreeNode> queue2=new LinkedList<TreeNode>();//下一层队列 if(root==null){ return; } queue.offer(root);//先把根节点入队,使队列不为空,进入循环 while(!queue.isEmpty()) { TreeNode node = queue.poll(); list.add(node.getData()); if (node.getLeftNode() != null) queue2.offer(node.getLeftNode()); if (node.getRightNode() != null) queue2.offer(node.getRightNode()); if (queue.isEmpty()) { treeList.add(list); list=new ArrayList<Integer>(); //链表用来存储每一层数据 queue.addAll(queue2); queue2.clear(); } } }
4、主函数输出list
public static void main(String[] args) {
TreeNode root=test.createTree();//调用了自己写的静态方法创建一棵树
wideSerch(root);
for(List<Integer> one:treeList){
System.out.println(one);
}
}
总结:
就是这么简单,一层一层的遍历。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。