java 二叉树先序_java 二叉树/创建/先序/中序/后序

代码如下:

package algorithm;

import java.util.LinkedList;

public class TwoForkTree {

//private int[] array = {1,2,3,4,5,6,7,8,9};

//private char[] array = {'a','b','c','d','e','f','g','h','i'};

private Object[] array = {'a','b','c','d','e','f','g','h','i'};

LinkedList linkedList = null;

private class Node {

Object data;

Node leftChild = null;

Node rightChild = null;

Node(Object data) {

this.data = data;

}

}

public void CreateBinTree() {

int parentIndex ;

linkedList = new LinkedList();

for(int i=0;i

linkedList.add(new Node(array[i]));

}

for(parentIndex = 0;parentIndex < array.length/2-1;parentIndex++) {

linkedList.get(parentIndex).leftChild = linkedList.get(parentIndex*2+1);

linkedList.get(parentIndex).rightChild = linkedList.get(parentIndex*2+2);

}

if(array.length % 2 == 0) {

linkedList.get(parentIndex).leftChild = linkedList.get(parentIndex*2+1);

} else {

linkedList.get(parentIndex).leftChild = linkedList.get(parentIndex*2+1);

linkedList.get(parentIndex).rightChild = linkedList.get(parentIndex*2+2);

}

}

//preOrderTraverse 先序遍历

public void preOrderTraverse(Node root) {

if(root==null)

return;

System.out.print(root.data + " ");

preOrderTraverse(root.leftChild);

preOrderTraverse(root.rightChild);

}

//preOrderTraverse 中序遍历

public void inOrderTraverse(Node root) {

if(root==null)

return;

inOrderTraverse(root.leftChild);

System.out.print(root.data + " ");

inOrderTraverse(root.rightChild);

}

//preOrderTraverse 后序遍历

public void postOrderTraverse(Node root) {

if(root==null)

return;

postOrderTraverse(root.leftChild);

postOrderTraverse(root.rightChild);

System.out.print(root.data + " ");

}

public static void main(String[] args) {

TwoForkTree twoForkTree = new TwoForkTree();

twoForkTree.CreateBinTree();

System.out.println("-----------------先序遍历---------------------");

twoForkTree.preOrderTraverse(twoForkTree.linkedList.get(0));

System.out.println("\n-----------------中序遍历---------------------");

twoForkTree.inOrderTraverse(twoForkTree.linkedList.get(0));

System.out.println("\n-----------------后序遍历---------------------");

twoForkTree.postOrderTraverse(twoForkTree.linkedList.get(0));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值