一天一個小演算法(02.二叉樹的層序遍歷)
import java.util.LinkedList;
import com.alibaba.fastjson.JSONObject;
public class BinaryNode {
private Object node;
private BinaryNode left;
private BinaryNode right;
/**
* 藉助於佇列來實現 藉助佇列的先進先出的特性
* 首先將根節點入佇列 然後遍歷佇列。
* 首先將根節點打印出來,接著判斷左節點是否為空 不為空則加入佇列
*/
public static void main(String[] args) {
BinaryNode node=createNode();
System.err.println(JSONObject.toJSONString(node));
LinkedList<BinaryNode>nodes=new LinkedList<BinaryNode>();
nodes.push(node);
BinaryNode current=null;
while(!nodes.isEmpty()) {
current=nodes.poll();
System.out.print(current.getNode()+"--->");
if(current.getLeft()!=null) {
nodes.offer(current.getLeft());
}
if(current.getRight()!=null) {
nodes.offer(current.getRight());
}
}
}
private static BinaryNode createNode() {
BinaryNode left3=new BinaryNode("30",null,null);
BinaryNode right3=new BinaryNode("31",null,null);
BinaryNode left2=new BinaryNode("20",null,null);
BinaryNode right2=new BinaryNode("21",null,null);
BinaryNode left=new BinaryNode("02",left2,right2);
BinaryNode right=new BinaryNode("03",left3,right3);
BinaryNode node=new BinaryNode("01",left,right);
return node;
}
public BinaryNode(Object node, BinaryNode left, BinaryNode right) {
super();
this.node = node;
this.left = left;
this.right = right;
}
public BinaryNode() {
}
public Object getNode() {
return node;
}
public void setNode(Object node) {
this.node = node;
}
public BinaryNode getLeft() {
return left;
}
public void setLeft(BinaryNode left) {
this.left = left;
}
public BinaryNode getRight() {
return right;
}
public void setRight(BinaryNode right) {
this.right = right;
}
}