您的位置:首页 > 编程语言 > Java开发

Java语言实现二叉树

2016-05-27 10:59 441 查看

Java语言实现二叉树

代码

import java.util.Scanner;

/**
* Java语言实现的二叉树结构
* 原理分析 主要采用递归思想
*
* @author tuzhao
* @github tuzhao
* @mail tuzhaocn@gmail.com
*/
public class BinaryTree {

public static class Node {
int item;
int count;
Node pLeft;
Node pRight;
}

public static void main(String[] args) {
int newValue = 0;
Node pRoot = null;
long answer = 0;

Scanner scanner = new Scanner(System.in);

do {
newValue = 0;
System.out.println("please enter the node value:   (-2147483648 -- 2147483647)");
newValue = scanner.nextInt();
if (pRoot == null) {
pRoot = createNode(newValue);
} else {
addNode(newValue, pRoot);
}

answer = 0;
System.out.println("do you want to enter another? 1 is yes! 0 is stop!");
answer = scanner.nextLong();
} while (answer == 1);

System.out.println("all the intput value is:");
listNodes(pRoot);
freeNodes(pRoot);
scanner.close();

}

public static Node createNode(int v) {
Node node = new Node();
node.item = v;
node.count = 1;
node.pLeft = null;
node.pRight = null;
return node;
}

public static Node addNode(int v, Node pNode) {
if (pNode == null) {
return createNode(v);
}

if (pNode.item == v) {
pNode.count++;
return pNode;
}

if (v < pNode.item) {
if (pNode.pLeft == null) {
pNode.pLeft = createNode(v);
return pNode.pLeft;
} else {
return addNode(v, pNode.pLeft);
}
} else {
if (pNode.pRight == null) {
pNode.pRight = createNode(v);
return pNode.pRight;
} else {
return addNode(v, pNode.pRight);
}
}
}

public static void listNodes(Node pNode) {
if (pNode.pLeft != null) {
listNodes(pNode.pLeft);
}

for (int i = 0; i < pNode.count; i++) {
System.out.println(pNode.item);
}

if (pNode.pRight != null) {
listNodes(pNode.pRight);
}

}

public static void freeNodes(Node pNode) {
if (pNode == null) {
return;
}
if (pNode.pLeft != null) {
freeNodes(pNode.pLeft);
}

if (pNode.pRight != null) {
freeNodes(pNode.pRight);
}

pNode = null;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 二叉树