这道题是指上考查树的遍历算法,只是这种遍历不是我们熟悉的前序、中序或者后序遍历。由于我们不太熟悉这种按层遍历的方法,可能一下子也想不清楚遍历的过程。那面试的时候怎么办呢。
我们从树的根节点开始分析,为了接下来能够打印值为8的节点和两个子节点,我们应该在遍历到该节点时把值为6和10的两个节点保存到一个容器里,现在容器内就有两个节点了。按照从左到右打印的要求,我们先取出值为6的节点。打印出值之后,把它的值分别为5和7两个节点放入数据容器,此时数据容器中有3个节点,值为10、5、7、接下来我们从数据容器中取出值为10的节点,注意到值为10的节点比值为5和7节点先放入容器,此时又比这两个节点先取出,这就是我们通常所说的先入先出,因此不难看出这个数据容器应该是一个队列。
package question32_print_tree;
import java.util.LinkedList;
import java.util.Queue;
/**
* @Classname Solution
* @Description TODO
* @Date 2020/3/27 16:25
* @Created by mmz
*/
public class Solution {
static class TreeNode{
int value ;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int value) {
this.value = value;
}
}
public static void printTree(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode treeNode = queue.poll();
System.out.println(treeNode.value);
if(treeNode.left !=null){
queue.add(treeNode.left);
}
if(treeNode.right != null){
queue.add(treeNode.right);
}
}
}
}
层次遍历
二刷
package question32_从上到下打印二叉树;
import question28_对称二叉树.MaIn;
import sun.reflect.generics.tree.Tree;
import java.util.LinkedList;
import java.util.Queue;
/**
* @Classname Main
* @Description TODO
* @Date 2020/4/11 23:25
* @Created by mmz
*/
public class Main {
static class TreeNode{
int val;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
@Override
public String toString() {
return "TreeNode{" +
"val=" + val +
", left=" + left +
", right=" + right +
'}';
}
}
static void Core(TreeNode root){
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()){
TreeNode now = queue.remove();
System.out.println(now.val);
if(now.left!= null){
queue.add(now.left);
}
if(now.right != null){
queue.add(now.right);
}
}
}
public static void main(String[] args) {
TreeNode one = new TreeNode(8);
TreeNode two = new TreeNode(8);
TreeNode three = new TreeNode(7);
TreeNode four = new TreeNode(9);
TreeNode five = new TreeNode(2);
TreeNode six = new TreeNode(4);
TreeNode seven = new TreeNode(7);
one.right = three;
one.left = two;
two.left = four;
two.right = five;
five.left = six;
five.right = seven;
Core(one);
}
}