博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java 层序创建和遍历二叉树
阅读量:4465 次
发布时间:2019-06-08

本文共 1922 字,大约阅读时间需要 6 分钟。

直接上代码

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;                //层序创建二叉树        LinkedList
queue = 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; }}

运行结果

1234831-20190407225749381-662575720.png

转载于:https://www.cnblogs.com/lick468/p/10667869.html

你可能感兴趣的文章
P1516 青蛙的约会 洛谷
查看>>
SDOI2011 染色
查看>>
JQuery EasyUI combobox动态添加option
查看>>
面向连接的TCP概述
查看>>
前端快捷方式 [记录]
查看>>
亲测可用,解决端口被占用的指令!!
查看>>
MySQL--视图、触发器、事务、存储过程、内置函数、流程控制、索引
查看>>
Django--数据库查询操作
查看>>
自定义配置文件的使用
查看>>
js-20170609-运算符
查看>>
算法笔记_065:分治法求逆序对(Java)
查看>>
MSP430FLASH小结
查看>>
STM32 ADC转换时间
查看>>
结合实际业务场景聊一聊MVP模式的应用
查看>>
WinPE启动U盘的制作方法与软件下载(通用PE工具箱/老毛桃/大白菜WinPE)(转载)...
查看>>
行为型设计模式之5--中介者模式
查看>>
Android DevArt6:Android中IPC的六种方式
查看>>
PMP学习感想
查看>>
Zookeeper全解析——Paxos作为灵魂
查看>>
集合-强大的集合工具类:java.util.Collections中未包含的集合工具
查看>>