从上到下打印二叉树
来源:互联网 发布:java解析pdf文件内容 编辑:程序博客网 时间:2024/06/05 06:38
import java.util.ArrayList;import java.util.LinkedList;import java.util.Queue;/** * 思路: 因为要按照顺序打印二叉树,所以在我们输出 * 根节点的值后,需要把当前结点的左右子树保存到队列中。 * 之后再从队列的头中取出结点,一直循环直到全部输出所有结点为止 * * 采用队列是因为队列是先进先出的结构 */public class PrintTtoB_BiTree { private static Queue<BiTree> queue = new LinkedList<>(); private static int a[] = {1,2,0,4,5,0,0,0,3,6,0,0,0}; static int length = 0; public static BiTree createBiTree1(BiTree T){ if (length == a.length) return null; int value = a[length++] ; if(value == 0) T = null; else{ T = new BiTree(); T.setValue(value); T.setmLeftChild(createBiTree1(T.mLeftChild)); T.setmRightChild(createBiTree1(T.mRightChild)); } return T; } public static BiTree createBiTree(BiTree root) { if (length < a.length) { int value = a[length++]; if (value == 0) { root = null; } else { BiTree lchild = new BiTree(); BiTree rchild = new BiTree(); root.value = value; root.mLeftChild = createBiTree(lchild); root.mRightChild = createBiTree(rchild); } } return root; } public static void PrintFromToptoBottom(BiTree biTree){ if (biTree == null) return; queue.add(biTree); while (queue.size() > 0){ System.out.println(queue.peek().value); biTree = queue.peek(); queue.poll(); if(biTree.getmLeftChild() != null) queue.add(biTree.getmLeftChild()); if(biTree.getmRightChild() != null) queue.add(biTree.getmRightChild()); } } public static void main(String[] args){ BiTree biTree = new BiTree(); createBiTree(biTree); PrintFromToptoBottom(biTree); } static class BiTree{ private int value; private BiTree mLeftChild; private BiTree mRightChild; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public BiTree getmLeftChild() { return mLeftChild; } public void setmLeftChild(BiTree mLeftChild) { this.mLeftChild = mLeftChild; } public BiTree getmRightChild() { return mRightChild; } public void setmRightChild(BiTree mRightChild) { this.mRightChild = mRightChild; } }}
0 0
- 从上到下打印二叉树
- 从上到下打印二叉树
- 从上到下打印二叉树
- 从上到下打印二叉树
- 从上到下打印二叉树
- 从上到下打印二叉树
- 从上到下打印二叉树
- 从上到下打印二叉树
- 从上到下打印二叉树-剑指offer23题
- C++ 从上到下,从左至右打印二叉树
- java之从上到下打印二叉树
- 从上到下按层打印二叉树
- 从上到下从左到右打印二叉树
- 题目23:从上到下打印二叉树
- 剑指offer23:从上到下打印二叉树
- 面试题 23: 从上到下打印二叉树
- 面试题23:从上到下打印二叉树
- 剑指offer21从上到下打印二叉树
- [Leetcode]_24 Swap Nodes in Pairs
- ToolBar实现滑动伸缩效果
- [C++]STL pair
- spoj Longest Common Substring II
- Google Chrome离线下载地址
- 从上到下打印二叉树
- 很容易输入不期望的输入
- 算法导论——24.1 BellmanFord算法java实现
- Java8特性系列文章目录
- String、StringBuffer、与StringBuilder的区别
- vector动态二维数组(容器的容器)占用内存分析
- 用vis.js库实现Neo4j的可视化
- MyBatis简介与配置MyBatis+Spring+MySql
- 如何将发布好的程序部署到IIS上