1、节点类
public class Node {
private int data;
private Node left;
private Node right;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}
2、分层遍历实现类
public class FindNode {
public void levelIterator(Node root) {
if(root == null) {
return ;
}
LinkedList queue = new LinkedList();
BiTree current = null;
queue.offer(root);//将根节点入队
while(!queue.isEmpty()) {
current = queue.poll();//出队队头元素并访问
System.out.print(current.val +"-->");
if(current.left != null)//如果当前节点的左节点不为空入队
{
queue.offer(current.left);
}
if(current.right != null)//如果当前节点的右节点不为空,把右节点入队
{
queue.offer(current.right);
}
}
}
}