二叉樹的相關(guān)操作,包括創(chuàng)建,中序、先序、后序(遞歸和非遞歸),其中重點(diǎn)的是java在先序創(chuàng)建二叉樹和后序非遞歸遍歷的的實(shí)現(xiàn)。
成都創(chuàng)新互聯(lián)服務(wù)熱線:028-86922220,為您提供成都網(wǎng)站建設(shè)網(wǎng)頁(yè)設(shè)計(jì)及定制高端網(wǎng)站建設(shè)服務(wù),成都創(chuàng)新互聯(lián)網(wǎng)頁(yè)制作領(lǐng)域10余年,包括成都PVC花箱等多個(gè)領(lǐng)域擁有多年設(shè)計(jì)經(jīng)驗(yàn),選擇成都創(chuàng)新互聯(lián),為企業(yè)錦上添花!
package com.algorithm.tree;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
import java.util.concurrent.LinkedBlockingQueue;
public class Tree {
private Node root;
public Tree() {
}
public Tree(Node root) {
this.root = root;
}
//創(chuàng)建二叉樹
public void buildTree() {
Scanner scn = null;
try {
scn = new Scanner(new File("input.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
root = createTree(root,scn);
}
//先序遍歷創(chuàng)建二叉樹
private Node createTree(Node node,Scanner scn) {
String temp = scn.next();
if (temp.trim().equals("#")) {
return null;
} else {
node = new Node((T)temp);
node.setLeft(createTree(node.getLeft(), scn));
node.setRight(createTree(node.getRight(), scn));
return node;
}
}
//中序遍歷(遞歸)
public void inOrderTraverse() {
inOrderTraverse(root);
}
public void inOrderTraverse(Node node) {
if (node != null) {
inOrderTraverse(node.getLeft());
System.out.println(node.getValue());
inOrderTraverse(node.getRight());
}
}
//中序遍歷(非遞歸)
public void nrInOrderTraverse() {
StackNode stack = new StackNode();
Node node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.getLeft();
}
node = stack.pop();
System.out.println(node.getValue());
node = node.getRight();
}
}
//先序遍歷(遞歸)
public void preOrderTraverse() {
preOrderTraverse(root);
}
public void preOrderTraverse(Node node) {
if (node != null) {
System.out.println(node.getValue());
preOrderTraverse(node.getLeft());
preOrderTraverse(node.getRight());
}
}
//先序遍歷(非遞歸)
public void nrPreOrderTraverse() {
StackNode stack = new StackNode();
Node node = root;
while (node != null || !stack.isEmpty()) {
while (node != null) {
System.out.println(node.getValue());
stack.push(node);
node = node.getLeft();
}
node = stack.pop();
node = node.getRight();
}
}
//后序遍歷(遞歸)
public void postOrderTraverse() {
postOrderTraverse(root);
}
public void postOrderTraverse(Node node) {
if (node != null) {
postOrderTraverse(node.getLeft());
postOrderTraverse(node.getRight());
System.out.println(node.getValue());
}
}
//后續(xù)遍歷(非遞歸)
public void nrPostOrderTraverse() {
StackNode stack = new StackNode();
Node node = root;
Node preNode = null;//表示最近一次訪問的節(jié)點(diǎn)
while (node != null || !stack.isEmpty()) {
while (node != null) {
stack.push(node);
node = node.getLeft();
}
node = stack.peek();
if (node.getRight() == null || node.getRight() == preNode) {
System.out.println(node.getValue());
node = stack.pop();
preNode = node;
node = null;
} else {
node = node.getRight();
}
}
}
//按層次遍歷
public void levelTraverse() {
levelTraverse(root);
}
public void levelTraverse(Node node) {
QueueNode queue = new LinkedBlockingQueueNode();
queue.add(node);
while (!queue.isEmpty()) {
Node temp = queue.poll();
if (temp != null) {
System.out.println(temp.getValue());
queue.add(temp.getLeft());
queue.add(temp.getRight());
}
}
}
}
//樹的節(jié)點(diǎn)
class Node {
private Node left;
private Node right;
private T value;
public Node() {
}
public Node(Node left,Node right,T value) {
this.left = left;
this.right = right;
this.value = value;
}
public Node(T value) {
this(null,null,value);
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}
}
測(cè)試代碼:
package com.algorithm.tree;
public class TreeTest {
/**
* @param args
*/
public static void main(String[] args) {
Tree tree = new Tree();
tree.buildTree();
System.out.println("中序遍歷");
tree.inOrderTraverse();
tree.nrInOrderTraverse();
System.out.println("后續(xù)遍歷");
//tree.nrPostOrderTraverse();
tree.postOrderTraverse();
tree.nrPostOrderTraverse();
System.out.println("先序遍歷");
tree.preOrderTraverse();
tree.nrPreOrderTraverse();
//
}
}
//******************************************************************************************************//
//*****本程序包括簡(jiǎn)單的二叉樹類的實(shí)現(xiàn)和前序,中序,后序,層次遍歷二叉樹算法,*******//
//******以及確定二叉樹的高度,制定對(duì)象在樹中的所處層次以及將樹中的左右***********//
//******孩子節(jié)點(diǎn)對(duì)換位置,返回葉子節(jié)點(diǎn)個(gè)數(shù)刪除葉子節(jié)點(diǎn),并輸出所刪除的葉子節(jié)點(diǎn)**//
//*******************************CopyRight By phoenix*******************************************//
//************************************Jan 12,2008*************************************************//
//****************************************************************************************************//
public class BinTree {
public final static int MAX=40;
private Object data; //數(shù)據(jù)元數(shù)
private BinTree left,right; //指向左,右孩子結(jié)點(diǎn)的鏈
BinTree []elements = new BinTree[MAX];//層次遍歷時(shí)保存各個(gè)節(jié)點(diǎn)
int front;//層次遍歷時(shí)隊(duì)首
int rear;//層次遍歷時(shí)隊(duì)尾
public BinTree()
{
}
public BinTree(Object data)
{ //構(gòu)造有值結(jié)點(diǎn)
this.data = data;
left = right = null;
}
public BinTree(Object data,BinTree left,BinTree right)
{ //構(gòu)造有值結(jié)點(diǎn)
this.data = data;
this.left = left;
this.right = right;
}
public String toString()
{
return data.toString();
}//前序遍歷二叉樹
public static void preOrder(BinTree parent){
if(parent == null)
return;
System.out.print(parent.data+" ");
preOrder(parent.left);
preOrder(parent.right);
}//中序遍歷二叉樹
public void inOrder(BinTree parent){
if(parent == null)
return;
inOrder(parent.left);
System.out.print(parent.data+" ");
inOrder(parent.right);
}//后序遍歷二叉樹
public void postOrder(BinTree parent){
if(parent == null)
return;
postOrder(parent.left);
postOrder(parent.right);
System.out.print(parent.data+" ");
}// 層次遍歷二叉樹
public void LayerOrder(BinTree parent)
{
elements[0]=parent;
front=0;rear=1;
while(frontrear)
{
try
{
if(elements[front].data!=null)
{
System.out.print(elements[front].data + " ");
if(elements[front].left!=null)
elements[rear++]=elements[front].left;
if(elements[front].right!=null)
elements[rear++]=elements[front].right;
front++;
}
}catch(Exception e){break;}
}
}//返回樹的葉節(jié)點(diǎn)個(gè)數(shù)
public int leaves()
{
if(this == null)
return 0;
if(left == nullright == null)
return 1;
return (left == null ? 0 : left.leaves())+(right == null ? 0 : right.leaves());
}//結(jié)果返回樹的高度
public int height()
{
int heightOfTree;
if(this == null)
return -1;
int leftHeight = (left == null ? 0 : left.height());
int rightHeight = (right == null ? 0 : right.height());
heightOfTree = leftHeightrightHeight?rightHeight:leftHeight;
return 1 + heightOfTree;
}
//如果對(duì)象不在樹中,結(jié)果返回-1;否則結(jié)果返回該對(duì)象在樹中所處的層次,規(guī)定根節(jié)點(diǎn)為第一層
public int level(Object object)
{
int levelInTree;
if(this == null)
return -1;
if(object == data)
return 1;//規(guī)定根節(jié)點(diǎn)為第一層
int leftLevel = (left == null?-1:left.level(object));
int rightLevel = (right == null?-1:right.level(object));
if(leftLevel0rightLevel0)
return -1;
levelInTree = leftLevelrightLevel?rightLevel:leftLevel;
return 1+levelInTree;
}
//將樹中的每個(gè)節(jié)點(diǎn)的孩子對(duì)換位置
public void reflect()
{
if(this == null)
return;
if(left != null)
left.reflect();
if(right != null)
right.reflect();
BinTree temp = left;
left = right;
right = temp;
}// 將樹中的所有節(jié)點(diǎn)移走,并輸出移走的節(jié)點(diǎn)
public void defoliate()
{
String innerNode = "";
if(this == null)
return;
//若本節(jié)點(diǎn)是葉節(jié)點(diǎn),則將其移走
if(left==nullright == null)
{
System.out.print(this + " ");
data = null;
return;
}
//移走左子樹若其存在
if(left!=null){
left.defoliate();
left = null;
}
//移走本節(jié)點(diǎn),放在中間表示中跟移走...
innerNode += this + " ";
data = null;
//移走右子樹若其存在
if(right!=null){
right.defoliate();
right = null;
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
BinTree e = new BinTree("E");
BinTree g = new BinTree("G");
BinTree h = new BinTree("H");
BinTree i = new BinTree("I");
BinTree d = new BinTree("D",null,g);
BinTree f = new BinTree("F",h,i);
BinTree b = new BinTree("B",d,e);
BinTree c = new BinTree("C",f,null);
BinTree tree = new BinTree("A",b,c);
System.out.println("前序遍歷二叉樹結(jié)果: ");
tree.preOrder(tree);
System.out.println();
System.out.println("中序遍歷二叉樹結(jié)果: ");
tree.inOrder(tree);
System.out.println();
System.out.println("后序遍歷二叉樹結(jié)果: ");
tree.postOrder(tree);
System.out.println();
System.out.println("層次遍歷二叉樹結(jié)果: ");
tree.LayerOrder(tree);
System.out.println();
System.out.println("F所在的層次: "+tree.level("F"));
System.out.println("這棵二叉樹的高度: "+tree.height());
System.out.println("--------------------------------------");
tree.reflect();
System.out.println("交換每個(gè)節(jié)點(diǎn)的孩子節(jié)點(diǎn)后......");
System.out.println("前序遍歷二叉樹結(jié)果: ");
tree.preOrder(tree);
System.out.println();
System.out.println("中序遍歷二叉樹結(jié)果: ");
tree.inOrder(tree);
System.out.println();
System.out.println("后序遍歷二叉樹結(jié)果: ");
tree.postOrder(tree);
System.out.println();
System.out.println("層次遍歷二叉樹結(jié)果: ");
tree.LayerOrder(tree);
System.out.println();
System.out.println("F所在的層次: "+tree.level("F"));
System.out.println("這棵二叉樹的高度: "+tree.height());
}
首先我想問為什么要用LinkedList 來(lái)建立二叉樹呢? LinkedList 是線性表,
樹是樹形的, 似乎不太合適。
其實(shí)也可以用數(shù)組完成,而且效率更高.
關(guān)鍵是我覺得你這個(gè)輸入本身就是一個(gè)二叉樹啊,
String input = "ABCDE F G";
節(jié)點(diǎn)編號(hào)從0到8. 層次遍歷的話:
對(duì)于節(jié)點(diǎn)i.
leftChild = input.charAt(2*i+1); //做子樹
rightChild = input.charAt(2*i+2);//右子樹
如果你要將帶有節(jié)點(diǎn)信息的樹存到LinkedList里面, 先建立一個(gè)節(jié)點(diǎn)類:
class Node{
public char cValue;
public Node leftChild;
public Node rightChild;
public Node(v){
this.cValue = v;
}
}
然后遍歷input,建立各個(gè)節(jié)點(diǎn)對(duì)象.
LinkedList tree = new LinkedList();
for(int i=0;i input.length;i++)
LinkedList.add(new Node(input.charAt(i)));
然后為各個(gè)節(jié)點(diǎn)設(shè)置左右子樹:
for(int i=0;iinput.length;i++){
((Node)tree.get(i)).leftChild = (Node)tree.get(2*i+1);
((Node)tree.get(i)).rightChild = (Node)tree.get(2*i+2);
}
這樣LinkedList 就存儲(chǔ)了整個(gè)二叉樹. 而第0個(gè)元素就是樹根,思路大體是這樣吧。