直接上代码
package te.com;import java.util.LinkedList;import java.util.Queue;import java.util.logging.Level;class BinNode{ Integer val; BinNode leftNode; BinNode rightNode; public BinNode(Integer val) { this.val = val; } public BinNode() { } public Integer getVal() { return val; } public void setVal(int val) { this.val = val; } public BinNode getLeftNode() { return leftNode; } public void setLeftNode(BinNode leftNode) { this.leftNode = leftNode; } public BinNode getRightNode() { return rightNode; } public void setRightNode(BinNode rightNode) { this.rightNode = rightNode; } }public class binTree { public static void main(String[] args) { Integer[] a = {3,9,20,null,null,15,7,null,null,null,null}; int i=1; BinNode root = new BinNode(a[0]); // 根节点 BinNode current = null; Integer value = null; //层序创建二叉树 LinkedListqueue = new LinkedList (); queue.offer(root); while(i queue = new LinkedList (); BinNode current = null; queue.offer(root); while(!queue.isEmpty()) { current = queue.poll(); if(current.getLeftNode()!=null) { queue.offer(current.getLeftNode()); System.out.println("节点"+current.val+"的左孩子是"+current.getLeftNode().val); }else { System.out.println("节点"+current.val+"没有左孩子"); } if(current.getRightNode()!=null) { queue.offer(current.getRightNode()); System.out.println("节点"+current.val+"的右孩子是"+current.getRightNode().val); }else { System.out.println("节点"+current.val+"没有右孩子"); } } return 1; }}
运行结果