二叉树的创建及遍历--java实现
2016-10-11 19:36
495 查看
关于二叉树,首先考虑的是二叉树的创建及遍历
参考网上的资料,结合自身的情况,给出二叉树的基本功能的java实现。
源码如下:
参考网上的资料,结合自身的情况,给出二叉树的基本功能的java实现。
源码如下:
//参考:http://www.linuxidc.com/Linux/2013-11/93170.htm
import java.util.LinkedList; class Node{ int val = 0; Node leftChild; Node rightChild; Node(int x) { val = x; } } public class binaryTree { private static Node root = null; private static int count = 0; public static void main(String[] args) { int[] vals ={1,2,4,0,0,5,0,0,3,0,0}; root = createBinaryTree(vals); preTraverseTree(root); System.out.println(); midTraverseTree(root); System.out.println(); levelTraverse(root); } // 使用先序创建一个二叉树 public static Node createBinaryTree(int[] values) { Node root = null; if (count >= values.length || values[count++]==0) { root = null; } else { root = new Node(values[count - 1]); root.leftChild = createBinaryTree(values); root.rightChild = createBinaryTree(values); } return root; } // 使用先序遍历一个二叉树 public static void preTraverseTree(Node root) { if (root == null) { System.out.print(0); }else{ System.out.print(root.val); preTraverseTree(root.leftChild); preTraverseTree(root.rightChild); } } // 使用中序遍历一个二叉树 public static void midTraverseTree(Node root) { if (root == null) { System.out.print(0); }else{ midTraverseTree(root.leftChild); System.out.print(root.val); midTraverseTree(root.rightChild); } } // 层次遍历一棵二叉树 public static void levelTraverse(Node root) { if(root == null){ return ; } LinkedList<Node> queue = new LinkedList<Node>(); Node current = null; queue.offer(root);//将根节点入队 while(!queue.isEmpty()){ current = queue.poll();//出队队头元素并访问 System.out.print(current.val +"-->"); if(current.leftChild != null){//如果当前节点的左节点不为空入队 queue.offer(current.leftChild); } if(current.rightChild != null){//如果当前节点的右节点不为空,把右节点入队 queue.offer(current.rightChild); } } } }
相关文章推荐
- 数据结构 — 二叉树(创建、遍历)java实现
- Java实现二叉树的创建、删除、遍历
- Java中创建二叉树并实现三种遍历方式
- Java实现二叉树的创建和遍历操作
- 二叉树(创建、前序、中序、后序、层序遍历理论及java实现)
- java实现二叉树的创建以及遍历
- Java实现二叉树创建及便遍历
- java实现二叉树的创建及5种遍历
- java创建二叉树并实现3种遍历(不使用类集)
- java实现二叉树的创建及三种递归遍历
- java实现二叉树的创建及5种遍历
- java实现二叉树的创建及遍历
- java实现二叉树的创建及5种遍历方法(总结)
- 大话数据结构(七)——二叉树创建与遍历(递归、非递归)的java实现
- 二叉树创建和遍历(Java版实现)
- java实现二叉树创建和遍历
- Java创建二叉树及其遍历的递归和非递归实现
- Java实现二叉树的创建和遍历操作(有更新)
- 数据结构二叉树的java实现,包括二叉树的创建、搜索、删除和遍历
- java实现二叉树的创建以及遍历