导航:首页 > 编程语言 > 二叉树镜像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相关的资料

热点内容
加密货币容易被盗 浏览:82
苹果平板如何开启隐私单个app 浏览:704
空调压缩机一开就停止 浏览:528
如何下载虎牙app 浏览:847
日语年号的算法 浏览:955
dev里面的编译日志咋调出来 浏览:298
php函数引用返回 浏览:816
文件夹和文件夹的创建 浏览:259
香港加密货币牌照 浏览:838
程序员鼓励自己的代码 浏览:393
计算机网络原理pdf 浏览:752
吃鸡国际体验服为什么服务器繁忙 浏览:94
php中sleep 浏览:490
vr怎么看视频算法 浏览:86
手机app如何申报个人所得税零申报 浏览:694
如何截获手机app连接的ip 浏览:332
冰箱压缩机是否需要电容 浏览:346
python列表每一行数据求和 浏览:276
自己有一台服务器可以玩什么 浏览:658
社会学波普诺pdf 浏览:585