树的层次遍历【队列的应用】
来源:互联网 发布:决策树源码 编辑:程序博客网 时间:2024/06/05 09:26
树的层次遍历【队列的应用】
思想:将不空的根节点入队列,队列不空的时候出队列,访问该节点,然后分别将左右孩子入队列,正好先出左,再出右,跟队列契合。
java实现代码;
package com.mytest.mymain;import java.util.LinkedList;import java.util.Queue;import java.util.Stack;class BTree{public int value; //public static int value; 那么最终输出都为8个8public BTree left; public BTree right; BTree(int x) { value = x; } }public class TraversalTree {public static void main(String[] args) {BTree root=new BTree(1);BTree Node2=new BTree(2);BTree Node3=new BTree(3);BTree Node4=new BTree(4);BTree Node5=new BTree(5);BTree Node6=new BTree(6);BTree Node7=new BTree(7);BTree Node8=new BTree(8);root.left=Node2;root.right=Node3;Node2.left=Node4;Node2.right=Node5;Node3.left=Node6;Node3.right=Node7;Node4.left=Node8;System.out.println("层次遍历");levelorder(root);}//层次遍历public static void levelorder(BTree root){Queue<BTree> queue=new LinkedList<BTree>();BTree bTree=null;if(root != null){queue.add(root);}while(!queue.isEmpty()){bTree=queue.poll();System.out.print(bTree.value+" ");if(bTree.left != null){queue.add(bTree.left);}if(bTree.right !=null ){queue.add(bTree.right);}}}}
0 0
- 树的层次遍历【队列的应用】
- 用队列实现树的层次遍历
- 二叉树的层次遍历 队列
- 二叉树的层次遍历---队列的使用
- 利用队列进行二叉树的层次遍历
- 二叉树的层次非递归遍历运用队列
- 层次遍历二叉树的方法(递归,队列,指针)
- 利用队列实现二叉树的层次遍历
- 树的层次遍历
- 树的层次遍历
- 树的层次遍历
- 树的层次遍历
- 树的层次遍历
- 树的层次遍历
- 树的层次遍历
- 树(5)二叉树层次遍历的应用
- 二叉树层次遍历的应用--改造二叉链表
- 树 层次 遍历 双队列
- 从jvm的角度来看单例模式
- gcc -lm 选项
- eclipse如何设置自动去除多余引入的类?
- 四种类型转换
- canvas的宽度设置
- 树的层次遍历【队列的应用】
- 《Java高并发程序设计》总结--5. 并行模式与算法
- react native搭建私有热更新服务器
- Java 多态
- 关于ibatis的总结
- 诚信&推荐【诺丁汉特伦特大学|毕业|】Nottingham Trent University (NTU)毕业颁发学历
- springmvc controller和servlet中文乱码问题
- 国际通行的打字速度评级标准
- Dama │ Juta8.com 10% First Deposit Extra Bonus