導航:首頁 > 編程語言 > 二叉樹鏡像java

二叉樹鏡像java

發布時間:2023-01-30 08:24:25

A. 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個元素就是樹根,思路大體是這樣吧。

B. 用java怎麼構造一個二叉樹

定義一個結點類:
public class Node {
private int value;
private Node leftNode;
private Node rightNode;

public Node getRightNode() {
return rightNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}

}

初始化結點樹:
public void initNodeTree()
{
int nodeNumber;
HashMap<String, Integer> map = new HashMap<String, Integer>();
Node nodeTree = new Node();

Scanner reader = new Scanner(System.in);

nodeNumber = reader.nextInt();
for(int i = 0; i < nodeNumber; i++) {
int value = reader.nextInt();
String str = reader.next();
map.put(str, value);
}

if (map.containsKey("#")) {
int value = map.get("#");
nodeTree.setValue(value);
setChildNode(map, value, nodeTree);
}

preTraversal(nodeTree);
}

private void setChildNode(HashMap<String, Integer> map, int nodeValue, Node parentNode) {
int value = 0;
if (map.containsKey("L" + nodeValue)) {
value = map.get("L" + nodeValue);
Node leftNode = new Node();
leftNode.setValue(value);
parentNode.setLeftNode(leftNode);

setChildNode(map, value, leftNode);
}

if (map.containsKey("R" + nodeValue)) {
value = map.get("R" + nodeValue);
Node rightNode = new Node();
rightNode.setValue(value);
parentNode.setRightNode(rightNode);

setChildNode(map, value, rightNode);
}
}

前序遍歷該結點樹:
public void preTraversal(Node nodeTree) {
if (nodeTree != null) {
System.out.print(nodeTree.getValue() + "\t");
preTraversal(nodeTree.getLeftNode());
preTraversal(nodeTree.getRightNode());
}
}

C. 怎麼用Java語言來實現二叉樹啊我現在編了一個程序卻不能運行出結果,誰能幫我!

終止搞定,inorder和postorder分別是中序和後序
public class Test
{
static String inorder = "287413695";//"BDEFACHG"; //已知中序
static String postorder = "874296531";//"FEDBHGCA"; //已知後序
static Node root;

static class Node
{
public Node(char divideChar)
{
this.data = divideChar;
}

Node left;
Node right;
char data;
}

static Node divide(String in,String post,Node node)
{
if (in == null || in.length() < 1 || post == null || post.length() < 1)
return null;

String left = "";
char divideChar = post.charAt(post.length()-1);

if(in.indexOf(divideChar) != -1)
left = in.substring(0, in.indexOf(divideChar));

String right = in.substring(in.indexOf(divideChar) + 1);

if(node == null)
root = node = new Node(divideChar);
else
node = new Node(divideChar);

if (left != null)
{
if(left.length() > 1)
node.left = divide(left, post.substring(0,left.length()),node);
else if(left.length() == 1)
node.left = new Node(left.charAt(0));
}

if (right != null)
{
if(right.length() > 1)
node.right = divide(right, post.substring(left.length(),post.length()-1),node);
else if(right.length() == 1)
node.right = new Node(right.charAt(0));
}
return node;
}

static void preorder(Node node)
{
if(node == null) return;
System.out.println(node.data);

if(node.left != null) preorder(node.left);
if(node.right != null) preorder(node.right);
}

public static void main(String[] args)
{
root = divide(inorder, postorder,root);
preorder(root); //列印前序
}
}

D. 怎樣用Java來體現二叉樹(順便加上注釋)

二叉樹,和資料庫的B樹操作流程是一樣的,例如:有如下欄位
F,C,B,H,K,I;
如果要形成二叉樹的話,則,首先取第一個數據作為根節點,所以,現在是 F ,如果欄位比根節點小,則保存在左子樹,如果比根節點大或者等於根節點則保存在右子樹,最後按左---根-----右輸出所以數據。
所以,實現的關鍵就是在於保存的數據上是否存在大小比較功能,而String類中compareTo()有這個能力,節點類要保存兩類數據,左節點,右節點
class Node
{
private String data;
private Node left;
private Node right;
public Node (String data){
this.data = data;
}
public void setLeft(Node left) {
this.left = left;
}
public void setRight(Node right){
this.right = right;
}
public String getDate() {
return this.data;
}
public Node getLeft(){
return this.left;
}
public Node getRight(){
return this.right;
}
public void addNode(Node newNode){
if(this.data.compareTo(newNode.data)>=0) {
if(this.left == null){
this.left = newNode;
}else {
this.left.addNode(newNode);
}
}else {
if(this.right == null) {
this.right = newNode;
} else {
this.right.addNode(newNode);
}
}
}
public void printNode(){
if(this.left!= null){
this.left.printNode();
}
System.out.println(this.data);
if(this.right != null){
this.right.printNode();
}
}
}
class BinaryTree
{
private Node root = null;
public void add(String data) {
Node newNode = new Node(data);
if(this.root == null) {
this.root = newNode;
}else{
this.root.addNode(newNode);
}
}
public void print() {
this.root.printNode();
}
}
public class Hello
{
public static void main (String args[]) {
BinaryTree link = new BinaryTree();
link.add("F");
link.add("C");
link.add("B");
link.add("H");
link.add("K");
link.add("I");
link.print();
}
}
你一看就英文就知道什麼意思了,應該可以理解了
這個二叉樹捉摸不透就別琢磨了,開放中一般用不上

}

E. 如何用java實現二叉樹

* 二叉樹的二叉鏈表結點定義 */
typedef char datatype;
typedef struct BiTNode
{
datatype data;
struct BiTNode * LChild , * RChild ;
} BiTNode , * BiTree ;

//數葉子結點的數目
/*
Author: WadeFelix RenV
*/
#include <stdio.h>
#include <stdlib.h>
#include "BinaryTree.h"
int countLeaf( BiTree BT )
{
if( BT == NULL ) return 0;
if( BT->LChild==NULL && BT->RChild==NULL ) return 1;
return(countLeaf(BT->LChild)+countLeaf(BT->RChild));
}

//數非葉子結點的數目

int countNotLeaf( BiTree BT )
{
if( BT == NULL ) return 0;
if( BT->LChild==NULL && BT->RChild==NULL ) return 0;
return(1+countNotLeaf(BT->LChild)+countNotLeaf(BT->RChild));
}

//判斷是否是排序二叉樹
#include <stdio.h>
#include <stdlib.h>
#include "BinaryTree.h"
int isPaiXu( BiTree BT )
{
if( BT == NULL )return 1;
if( BT->LChild && (BT->LChild->data > BT->data) )return 0;
if( BT->RChild && (BT->RChild->data < BT->data) )return 0;

return( isPaiXu(BT->LChild)&&isPaiXu(BT->RChild) );
}
看看對不對、

F. 用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();
}
}

G. 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);

H. java構建二叉樹演算法

下面是你第一個問題的解法,是構建了樹以後又把後序輸出的程序。以前寫的,可以把輸出後序的部分刪除,還有檢驗先序中序的輸入是否合法的代碼也可以不要。/*****TreeNode.java*********/public class TreeNode {
char elem;
TreeNode left;
TreeNode right;
}/*******PlantTree.java*********/import java.io.*;
public class PlantTree {
TreeNode root;
public static void main(String[] args) {
PlantTree seed=new PlantTree();
String preorder=null;
String inorder=null;
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please input the preorder");
preorder=br.readLine();
System.out.println("Please input the inorder");
inorder=br.readLine();
} catch (Exception e) {
// TODO: handle exception
}

if(preorder!=null&&seed.checkTree(preorder,inorder)) {

seed.root=new TreeNode();
seed.root.elem=preorder.charAt(0);
seed.makeTree(preorder,inorder,seed.root);
System.out.println("The tree has been planted,the postorder is:");
seed.printPostorder(seed.root);
}
}

void makeTree(String preorder,String inorder,TreeNode root) {
int i=inorder.lastIndexOf(root.elem);

if(i!=0) {//有左子樹
String leftPre=preorder.substring(1, i+1);
String leftIn=inorder.substring(0,i);
TreeNode leftNode=new TreeNode();
leftNode.elem=leftPre.charAt(0);
root.left=leftNode;
makeTree(leftPre,leftIn,leftNode);
}
if(i!=inorder.length()-1) {//有右子樹
String rightPre=preorder.substring(i+1,preorder.length());
String rightIn=inorder.substring(i+1,inorder.length());
TreeNode rightNode=new TreeNode();
rightNode.elem=rightPre.charAt(0);
root.right=rightNode;
makeTree(rightPre,rightIn,rightNode);
}

}
void printPostorder(TreeNode root) {
if(root.left!=null)
printPostorder(root.left);
if(root.right!=null)
printPostorder(root.right);
System.out.print(root.elem);

}
boolean checkTree(String a,String b) {
for(int i=0;i<a.length();i++) {
if(i!=a.lastIndexOf(a.charAt(i))) {
System.out.println("There are same element in the tree");
return false;
}
if(!b.contains(""+a.charAt(i))) {
System.out.println("Invalid input");
return false;
}

}
if(a.length()==b.length())
return true;
return false;
}
}

I. java如何創建一顆二叉樹

計算機科學中,二叉樹是每個結點最多有兩個子樹的有序樹。通常子樹的根被稱作「左子樹」(left subtree)和「右子樹」(right subtree)。二叉樹常被用作二叉查找樹和二叉堆或是二叉排序樹。

二叉樹的每個結點至多隻有二棵子樹(不存在度大於2的結點),二叉樹的子樹有左右之分,次序不能顛倒。二叉樹的第i層至多有2的 i -1次方個結點;深度為k的二叉樹至多有2^(k) -1個結點;對任何一棵二叉樹T,如果其終端結點數(即葉子結點數)為n0,度為2的結點數為n2,則n0 = n2 + 1。

樹是由一個或多個結點組成的有限集合,其中:

⒈必有一個特定的稱為根(ROOT)的結點;

二叉樹
⒉剩下的結點被分成n>=0個互不相交的集合T1、T2、......Tn,而且, 這些集合的每一個又都是樹。樹T1、T2、......Tn被稱作根的子樹(Subtree)。

樹的遞歸定義如下:(1)至少有一個結點(稱為根)(2)其它是互不相交的子樹

1.樹的度——也即是寬度,簡單地說,就是結點的分支數。以組成該樹各結點中最大的度作為該樹的度,如上圖的樹,其度為2;樹中度為零的結點稱為葉結點或終端結點。樹中度不為零的結點稱為分枝結點或非終端結點。除根結點外的分枝結點統稱為內部結點。

2.樹的深度——組成該樹各結點的最大層次。

3.森林——指若干棵互不相交的樹的集合,如上圖,去掉根結點A,其原來的二棵子樹T1、T2、T3的集合{T1,T2,T3}就為森林;

4.有序樹——指樹中同層結點從左到右有次序排列,它們之間的次序不能互換,這樣的樹稱為有序樹,否則稱為無序樹。

樹的表示
樹的表示方法有許多,常用的方法是用括弧:先將根結點放入一對圓括弧中,然後把它的子樹由左至右的順序放入括弧中,而對子樹也採用同樣的方法處理;同層子樹與它的根結點用圓括弧括起來,同層子樹之間用逗號隔開,最後用閉括弧括起來。如右圖可寫成如下形式:
二叉樹
(a( b(d,e), c( f( ,g(h,i) ), )))

J. 說明生活中遇到的二叉樹,用java實現二叉樹. (求源碼,要求簡練、易懂。非常滿意會額外加分)

import java.util.ArrayList;

// 樹的一個節點
class TreeNode {

Object _value = null; // 他的值
TreeNode _parent = null; // 他的父節點,根節點沒有PARENT
ArrayList _childList = new ArrayList(); // 他的孩子節點

public TreeNode( Object value, TreeNode parent ){
this._parent = parent;
this._value = value;
}

public TreeNode getParent(){
return _parent;
}

public String toString() {
return _value.toString();
}
}

public class Tree {

// 給出寬度優先遍歷的值數組,構建出一棵多叉樹
// null 值表示一個層次的結束
// "|" 表示一個層次中一個父親節點的孩子輸入結束
// 如:給定下面的值數組:
// { "root", null, "left", "right", null }
// 則構建出一個根節點,帶有兩個孩子("left","right")的樹
public Tree( Object[] values ){
// 創建根
_root = new TreeNode( values[0], null );

// 創建下面的子節點
TreeNode currentParent = _root; // 用於待創建節點的父親
//TreeNode nextParent = null;
int currentChildIndex = 0; // 表示 currentParent 是他的父親的第幾個兒子
//TreeNode lastNode = null; // 最後一個創建出來的TreeNode,用於找到他的父親
for ( int i = 2; i < values.length; i++ ){

// 如果null ,表示下一個節點的父親是當前節點的父親的第一個孩子節點
if ( values[i] == null ){
currentParent = (TreeNode)currentParent._childList.get(0);
currentChildIndex = 0;
continue;
}

// 表示一個父節點的所有孩子輸入完畢
if ( values[i].equals("|") ){
if ( currentChildIndex+1 < currentParent._childList.size() ){
currentChildIndex++;
currentParent = (TreeNode)currentParent._parent._childList.get(currentChildIndex);
}
continue;
}

TreeNode child = createChildNode( currentParent, values[i] );
}
}

TreeNode _root = null;

public TreeNode getRoot(){
return _root;
}
/**
// 按寬度優先遍歷,列印出parent子樹所有的節點
private void printSteps( TreeNode parent, int currentDepth ){
for ( int i = 0; i < parent._childList.size(); i++ ){
TreeNode child = (TreeNode)parent._childList.get(i);
System.out.println(currentDepth+":"+child);
}
if ( parent._childList.size() != 0 ) System.out.println(""+null);// 為了避免葉子節點也會列印null

//列印 parent 同層的節點的孩子
if ( parent._parent != null ){ // 不是root
int i = 1;
while ( i < parent._parent._childList.size() ){// parent 的父親還有孩子
TreeNode current = (TreeNode)parent._parent._childList.get(i);
printSteps( current, currentDepth );
i++;
}
}

// 遞歸調用,列印所有節點
for ( int i = 0; i < parent._childList.size(); i++ ){
TreeNode child = (TreeNode)parent._childList.get(i);
printSteps( child, currentDepth+1 );
}

}

// 按寬度優先遍歷,列印出parent子樹所有的節點
public void printSteps(){
System.out.println(""+_root);
System.out.println(""+null);

printSteps(_root, 1 );
}**/

// 將給定的值做為 parent 的孩子,構建節點
private TreeNode createChildNode( TreeNode parent, Object value ){
TreeNode child = new TreeNode( value , parent );
parent._childList.add( child );
return child;
}

public static void main(String[] args) {

Tree tree = new Tree( new Object[]{ "root", null,
"left", "right", null,
"l1","l2","l3", "|", "r1","r2",null } );
//tree.printSteps();

System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(0) )._childList.get(0) );
System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(0) )._childList.get(1) );
System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(0) )._childList.get(2) );

System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(1) )._childList.get(0) );
System.out.println(""+ ( (TreeNode)tree.getRoot()._childList.get(1) )._childList.get(1) );

}

}

看一下吧!這是在網上找的一個例子!看對你有沒有幫助!

閱讀全文

與二叉樹鏡像java相關的資料

熱點內容
考駕照怎麼找伺服器 瀏覽:882
阿里雲伺服器如何更換地區 瀏覽:970
手機app調音器怎麼調古箏 瀏覽:501
銳起無盤系統在伺服器上需要設置什麼嗎 瀏覽:17
紅旗計程車app怎麼應聘 瀏覽:978
如何編寫linux程序 瀏覽:870
吉利車解壓 瀏覽:248
java輸入流字元串 瀏覽:341
安卓軟體沒網怎麼回事 瀏覽:785
dvd壓縮碟怎麼導出電腦 瀏覽:274
冒險島什麼伺服器好玩 瀏覽:541
如何在伺服器上做性能測試 瀏覽:793
命令序列錯 瀏覽:259
javaif的條件表達式 瀏覽:576
手機app上傳的照片怎麼找 瀏覽:531
雲伺服器面臨哪些威脅 瀏覽:748
c語言各種編譯特點 瀏覽:177
路由器多種加密方法 瀏覽:604
程序員阻止電腦自動彈出定位 瀏覽:168
如何做伺服器服務商 瀏覽:763