java二叉樹實現
① 如何用java實現二叉樹
import java.util.List;
import java.util.LinkedList;
public class Bintrees {
private int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9};
private static List<Node> nodeList = null;
private static class Node {
Node leftChild;
Node rightChild;
int data;
Node(int newData) {
leftChild = null;
rightChild = null;
data = newData;
}
}
// 創建二叉樹
public void createBintree() {
nodeList = new LinkedList<Node>();
// 將數組的值轉換為node
for (int nodeIndex = 0; nodeIndex < array.length; nodeIndex++) {
nodeList.add(new Node(array[nodeIndex]));
}
// 對除最後一個父節點按照父節點和孩子節點的數字關系建立二叉樹
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 void preOrderTraverse(Node node) {
if (node == null) {
return;
}
System.out.print(node.data + " ");
preOrderTraverse(node.leftChild);
preOrderTraverse(node.rightChild);
}
// 中序遍歷
public static void inOrderTraverse(Node node) {
if (node == null) {
return;
}
inOrderTraverse(node.leftChild);
System.out.print(node.data + " ");
inOrderTraverse(node.rightChild);
}
// 後序遍歷
public static void postOrderTraverse(Node node) {
if (node == null) {
return;
}
postOrderTraverse(node.leftChild);
postOrderTraverse(node.rightChild);
System.out.print(node.data + " ");
}
public static void main(String[] args) {
Bintrees binTree = new Bintrees();
binTree.createBintree();
Node root = nodeList.get(0);
System.out.println("前序遍歷:");
preOrderTraverse(root);
System.out.println();
System.out.println("中序遍歷:");
inOrderTraverse(root);
System.out.println();
System.out.println("後序遍歷:");
postOrderTraverse(root);
}
}
輸出結果:
前序遍歷:
1 2 4 8 9 5 3 6 7
中序遍歷:
8 4 9 2 5 1 6 3 7
後序遍歷:
8 9 4 5 2 6 7 3 1
② 用java實現二叉樹
我有很多個(假設10萬個)數據要保存起來,以後還需要從保存的這些數據中檢索是否存在某
個數據,(我想說出二叉樹的好處,該怎麼說呢?那就是說別人的缺點),假如存在數組中,
那麼,碰巧要找的數字位於99999那個地方,那查找的速度將很慢,因為要從第1個依次往
後取,取出來後進行比較。平衡二叉樹(構建平衡二叉樹需要先排序,我們這里就不作考慮
了)可以很好地解決這個問題,但二叉樹的遍歷(前序,中序,後序)效率要比數組低很多,
public class Node {
public int value;
public Node left;
public Node right;
public void store(intvalue)
right.value=value;
}
else
{
right.store(value);
}
}
}
public boolean find(intvalue)
{
System.out.println("happen" +this.value);
if(value ==this.value)
{
return true;
}
else if(value>this.value)
{
if(right ==null)returnfalse;
return right.find(value);
}else
{
if(left ==null)returnfalse;
return left.find(value);
}
}
public void preList()
{
System.out.print(this.value+ ",");
if(left!=null)left.preList();
if(right!=null) right.preList();
}
public void middleList()
{
if(left!=null)left.preList();
System.out.print(this.value+ ",");
if(right!=null)right.preList();
}
public void afterList()
{
if(left!=null)left.preList();
if(right!=null)right.preList();
System.out.print(this.value+ ",");
}
public static voidmain(String [] args)
{
int [] data =new int[20];
for(inti=0;i<data.length;i++)
{
data[i] = (int)(Math.random()*100)+ 1;
System.out.print(data[i] +",");
}
System.out.println();
Node root = new Node();
root.value = data[0];
for(inti=1;i<data.length;i++)
{
root.store(data[i]);
}
root.find(data[19]);
root.preList();
System.out.println();
root.middleList();
System.out.println();
root.afterList();
}
}
③ java怎麼實現二叉樹
這是一段代碼:
就是java樹
privatevoidjbInit()throwsException{
contentPane=(JPanel)getContentPane();
contentPane.setLayout(null);
setSize(newDimension(450,350));
setTitle("WelcometoJTree");
//CreatingRootnode
DefaultMutableTreeNoderoot=newDefaultMutableTreeNode("根節點");
//CreatingParentnode
DefaultMutableTreeNodeparent=newDefaultMutableTreeNode("書籍");
lblNode.setFont(newjava.awt.Font("Tahoma",Font.PLAIN,11));
lblNode.setText("NodeName:");
lblNode.setBounds(newRectangle(202,115,59,14));
txtNode.setFont(newjava.awt.Font("Tahoma",Font.PLAIN,11));
txtNode.setText("");
txtNode.setBounds(newRectangle(322,112,117,20));
txtName.setFont(newjava.awt.Font("Tahoma",Font.PLAIN,11));
contentPane.setMaximumSize(newDimension(600,400));
contentPane.setPreferredSize(newDimension(600,400));
root.add(parent);
//CreatingLeafnodes
DefaultMutableTreeNodejava=newDefaultMutableTreeNode("Java");
parent.add(java);
=newDefaultMutableTreeNode(
"CompleteReference");
java.add(complete);
=newDefaultMutableTreeNode(
"JavaProgramming");
java.add(professional);
=newDefaultMutableTreeNode(
"AdvancedJavaProgramming");
java.add(advanced);
DefaultMutableTreeNodeoracle=newDefaultMutableTreeNode("Oracle");
parent.add(oracle);
DefaultMutableTreeNodelearn=newDefaultMutableTreeNode(
"LearningOracle");
oracle.add(learn);
DefaultMutableTreeNodesql=newDefaultMutableTreeNode("LearningSQL");
oracle.add(sql);
DefaultMutableTreeNodeplsql=newDefaultMutableTreeNode(
"LearningSQL/PLSQL");
oracle.add(learn);
DefaultMutableTreeNodeprogram=newDefaultMutableTreeNode(
"LearningProgramming");
oracle.add(program);
DefaultMutableTreeNodejsp=newDefaultMutableTreeNode("JSP");
parent.add(jsp);
DefaultMutableTreeNodejsp1=
newDefaultMutableTreeNode("LearningJSP");
jsp.add(jsp1);
DefaultMutableTreeNodejsp2=newDefaultMutableTreeNode(
"ProgrammingInJSP");
jsp.add(jsp2);
DefaultMutableTreeNodeleaf=newDefaultMutableTreeNode("C#");
parent.add(leaf);
=newDefaultMutableTreeNode(
"ProgrammingInC#");
leaf.add(programming);
//CreatinganotherBranchnode
parent=newDefaultMutableTreeNode("軟體");
root.add(parent);
//CreatingLeafnodes
leaf=newDefaultMutableTreeNode("OperatingSystem");
parent.add(leaf);
DefaultMutableTreeNodedosObj=newDefaultMutableTreeNode("MS-DOS");
leaf.add(dosObj);
=newDefaultMutableTreeNode(
"Windows2000Server");
leaf.add(windowsObj);
DefaultMutableTreeNodewinObj=newDefaultMutableTreeNode(
"Windows2000Professional");
leaf.add(winObj);
leaf=newDefaultMutableTreeNode("Database");
parent.add(leaf);
=newDefaultMutableTreeNode(
"MS-Access");
leaf.add(accessObj);
=newDefaultMutableTreeNode(
"MS-SQLServer");
leaf.add(mssqlObj);
④ java 構建二叉樹
首先我想問為什麼要用LinkedList 來建立二叉樹呢? LinkedList 是線性表,
樹是樹形的, 似乎不太合適。
其實也可以用數組完成,而且效率更高.
關鍵是我覺得你這個輸入本身就是一個二叉樹啊,
String input = "ABCDE F G";
節點編號從0到8. 層次遍歷的話:
對於節點i.
leftChild = input.charAt(2*i+1); //做子樹
rightChild = input.charAt(2*i+2);//右子樹
如果你要將帶有節點信息的樹存到LinkedList裡面, 先建立一個節點類:
class Node{
public char cValue;
public Node leftChild;
public Node rightChild;
public Node(v){
this.cValue = v;
}
}
然後遍歷input,建立各個節點對象.
LinkedList tree = new LinkedList();
for(int i=0;i< input.length;i++)
LinkedList.add(new Node(input.charAt(i)));
然後為各個節點設置左右子樹:
for(int i=0;i<input.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 就存儲了整個二叉樹. 而第0個元素就是樹根,思路大體是這樣吧。
⑤ 如何用java實現二叉樹的構建
樹的構建方法
注意:
1. 父節點數組下標從0到 n/2 -1 ,但是遍歷時要小於n/2-1,因回為最後一個父節點可能沒有答右孩子,當n/2-1為奇數時才有右孩子,為偶數時只有左孩子。
2. 結點左孩子下標為2n+1,右孩子下標為2n+2。
⑥ 求Java實現二叉樹!!!
程序設計模塊的問題都這樣呢.......
先把自己完成的部分寫出來吧 可以幫你看看問題所在 沒那麼多時間幫你編整段代碼啊
⑦ 二叉樹的java實現與幾種遍歷
二叉樹的定義
二叉樹(binary tree)是結點的有限集合,這個集合或者空,或者由一個根及兩個互不相交的稱為這個根的左子樹或右子樹構成.
從定義可以看出,二叉樹包括:1.空樹 2.只有一個根節點 3.只有左子樹 4.只有右子樹 5.左右子樹都存在 有且僅有這5種表現形式
二叉樹的遍歷分為三種:前序遍歷 中序遍歷 後序遍歷
前序遍歷:按照「根左右」,先遍歷根節點,再遍歷左子樹 ,再遍歷右子樹
中序遍歷:按照「左根右「,先遍歷左子樹,再遍歷根節點,最後遍歷右子樹
後續遍歷:按照「左右根」,先遍歷左子樹,再遍歷右子樹,最後遍歷根節點
其中前,後,中指的是每次遍歷時候的根節點被遍歷的順序
具體實現看下圖:
⑧ java實現二叉樹的問題
/**
* 二叉樹測試二叉樹順序存儲在treeLine中,遞歸前序創建二叉樹。另外還有能
* 夠前序、中序、後序、按層遍歷二叉樹的方法以及一個返回遍歷結果asString的
* 方法。
*/
public class BitTree {
public static Node2 root;
public static String asString;
//事先存入的數組,符號#表示二叉樹結束。
public static final char[] treeLine = {'a','b','c','d','e','f','g',' ',' ','j',' ',' ','i','#'};
//用於標志二叉樹節點在數組中的存儲位置,以便在創建二叉樹時能夠找到節點對應的數據。
static int index;
//構造函數
public BitTree() {
System.out.print("測試二叉樹的順序表示為:");
System.out.println(treeLine);
this.index = 0;
root = this.setup(root);
}
//創建二叉樹的遞歸程序
private Node2 setup(Node2 current) {
if (index >= treeLine.length) return current;
if (treeLine[index] == '#') return current;
if (treeLine[index] == ' ') return current;
current = new Node2(treeLine[index]);
index = index * 2 + 1;
current.left = setup(current.left);
index ++;
current.right = setup(current.right);
index = index / 2 - 1;
return current;
}
//二叉樹是否為空。
public boolean isEmpty() {
if (root == null) return true;
return false;
}
//返回遍歷二叉樹所得到的字元串。
public String toString(int type) {
if (type == 0) {
asString = "前序遍歷:\t";
this.front(root);
}
if (type == 1) {
asString = "中序遍歷:\t";
this.middle(root);
}
if (type == 2) {
asString = "後序遍歷:\t";
this.rear(root);
}
if (type == 3) {
asString = "按層遍歷:\t";
this.level(root);
}
return asString;
}
//前序遍歷二叉樹的循環演算法,每到一個結點先輸出,再壓棧,然後訪問它的左子樹,
//出棧,訪問其右子樹,然後該次循環結束。
private void front(Node2 current) {
StackL stack = new StackL((Object)current);
do {
if (current == null) {
current = (Node2)stack.pop();
current = current.right;
} else {
asString += current.ch;
current = current.left;
}
if (!(current == null)) stack.push((Object)current);
} while (!(stack.isEmpty()));
}
//中序遍歷二叉樹
private void middle(Node2 current) {
if (current == null) return;
middle(current.left);
asString += current.ch;
middle(current.right);
}
//後序遍歷二叉樹的遞歸演算法
private void rear(Node2 current) {
if (current == null) return;
rear(current.left);
rear(current.right);
asString += current.ch;
}
}
/**
* 二叉樹所使用的節點類。包括一個值域兩個鏈域
*/
public class Node2 {
char ch;
Node2 left;
Node2 right;
//構造函數
public Node2(char c) {
this.ch = c;
this.left = null;
this.right = null;
}
//設置節點的值
public void setChar(char c) {
this.ch = c;
}
//返回節點的值
public char getChar() {
return ch;
}
//設置節點的左孩子
public void setLeft(Node2 left) {
this.left = left;
}
//設置節點的右孩子
public void setRight (Node2 right) {
this.right = right;
}
//如果是葉節點返回true
public boolean isLeaf() {
if ((this.left == null) && (this.right == null)) return true;
return false;
}
}
一個作業題,裡面有你要的東西。
主函數自己寫吧。當然其它地方也有要改的。
⑨ java二叉樹家譜實現
mport java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class Randomtree extends JFrame {
private JTree tree;
public static String[] school = { "初中課程", "高中課程", "大學課程" };
public static String[] color = { "顏色", "運動", "食物" };
public static String[] plant = { "植物", "動物", "人" };
public static String[][] school2= {
{ "初中一年級", "初中二年級", "初中三年級"}, {"高中一年級", "高中二年級",
"高中三年級"}, {"大學一年級", "大學二年級", "大學三年級", "大學四年級"} };
public static String[][] color2 = {
{ "綠色", "白色", "紅色"}, {"足球", "籃球",
"羽毛球"}, {"麵包", "牛奶", "披薩", "熱狗"} };
public static String[][] plant2 = {
{ "玫瑰花", "月季花", "海棠花"}, {"豬", "狗",
"貓"}, {"黃種人", "黑種人", "白種人", } };
public static void main(String[] args) {
// TODO 自動生成方法存根
new Randomtree();
}
public Randomtree() {
super();
final Random random=new Random();
setVisible(true);
setSize(300,400);
tree = new JTree();
final JPanel panel = new JPanel();
panel.setPreferredSize(new Dimension(0, 40));
getContentPane().add(panel, BorderLayout.NORTH);
final JScrollPane scrollPane = new JScrollPane();
scrollPane.setPreferredSize(new Dimension(300, 350));
getContentPane().add(scrollPane, BorderLayout.CENTER);
final JButton button = new JButton();
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
int k=random.nextInt(3);
tree=getTree(k);
scrollPane.setViewportView(tree);
}
});
scrollPane.setViewportView(null);
button.setText("隨機生成樹");
panel.add(button);
pack();
}
protected JTree getTree(int n) {
String[] second=null;
String[][] three=null;
if(n==0){second=school; three=school2;}
if(n==1){second=color; three=color2;}
if(n==2){second=plant; three=plant2;}
DefaultMutableTreeNode root=new DefaultMutableTreeNode("root");
for(int i=0;i<second.length;i++){
DefaultMutableTreeNode secondNode=new DefaultMutableTreeNode(second[i]);
for (int j=0;j<three[i].length;j++){
DefaultMutableTreeNode threetNode=new DefaultMutableTreeNode(three[i][j]);
secondNode.add(threetNode);
}
root.add(secondNode);
}
JTree tree=new JTree(root);
tree.expandRow(1);
tree.expandRow(5);
tree.expandRow(9);
return tree;
}
}
簡單的 例子你可以模仿一下