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;
}
}