JAVA实现二叉树的前序遍历、中序遍历、后序遍历和层次遍历算法

发布时间:2019-05-07 07:24:17   来源:文档文库   
字号:

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

JAVA 实现二叉树的前序遍历、中序遍历、后序遍历和层次遍历算法

JAVA 实现二叉树的前序遍历、中序遍历、后序遍历和层次遍历算法 如图所

示一颗二叉树,用 JAVA 实现二叉树的前序遍历、中序遍历、后序遍历和层次遍历

算法

定义树节点

public class TreeNode { int data; TreeNode leftChild; TreeNode rightChild;

TreeNode(){ this.leftChild=null; this.rightChild=null; this.data=-1; TreeNode(int data){

this.leftChild=null; this.rightChild=null; this.data=data; public TreeNode(int data,

TreeNode leftChild, TreeNode rightChild) { this.data = data; this.leftChild = leftChild;

this.rightChild = rightChild; //其它代码省略…… 二叉树的前序遍历、中序遍历、后

序遍历和层次遍历算法设计

package com.bean.binarytreedemo;import java.util.List;import

java.util.LinkedList;import java.util.List;import java.util.Queue;import java.util.Stack; //

定一个一维数组,表示二叉树节点的值 private int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

private static List TreeNode nodeList = null; public void createBinTree() { nodeList =

new LinkedList TreeNode // 将一个数组的值依次转换为 Node 节点 for (int

nodeIndex = 0; nodeIndex array.length; nodeIndex++) { nodeList.add(new

TreeNode(array[nodeIndex])); // 对前 lastParentIndex-1 个父节点按照父节点与孩子

节点的数字关系建立二叉树 for (int parentIndex = 0; parentIndex array.length / 2 - 1;

parentIndex++) { // 左孩子 nodeList.get(parentIndex).leftChild =

nodeList .get(parentIndex * 2 + 1); // 右孩子 nodeList.get(parentIndex).rightChild =

nodeList .get(parentIndex * 2 + 2); // 最后一个父节点:因为最后一个父节点可能没

有右孩子,因此单独拿出来处理 int lastParentIndex = array.length / 2 - 1; // 左孩子

nodeList.get(lastParentIndex).leftChild = nodeList .get(lastParentIndex * 2 + 1); //

孩子,如果数组的长度为奇数才建立右孩子 if (array.length % 2 == 1) {

本文由我司收集整编,推荐下载,如有疑问,请与我司联系

nodeList.get(lastParentIndex).rightChild = nodeList .get(lastParentIndex * 2 + 2);

public static List Integer preOrder(TreeNode root){ Stack TreeNode stack = new

本文来源:https://www.2haoxitong.net/k/doc/562190e203768e9951e79b89680203d8ce2f6aef.html

《JAVA实现二叉树的前序遍历、中序遍历、后序遍历和层次遍历算法.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

文档为doc格式