导航:首页 > 编程语言 > 用java实现二叉树实现插入

用java实现二叉树实现插入

发布时间:2022-05-24 05:38:26

1. java二叉树前序方法增加一个新的节点,然后把另一个节点的数据插入到这个新节点

叶子节点:没有孩子节点的节点也就是说,当我们明白了叶子节点的定义后,只需要遍历一遍二叉树,把符合这种条件(左孩子节点和右孩子节点都为NULL的节点)的节点统计出来就可以了。于是,实际上这个问题也就转化成了如何遍历二叉树?很显然,遍历二叉树是可以有多种方式的,如:前序遍历(递归/非递归)、中序遍历(递归/非递归)、后序遍历(递归/非递归)、层次遍历等等。下面我将给出使用递归前序遍历以及层次遍历两种思路实现的求解叶子节点的示例代码吧,仅供参考。其他几种实现方式思路类似,可自行尝试。示例代码如下:package cn.zifangsky.tree.questions;import org.junit.Test;import cn.zifangsky.queue.LinkQueue;import cn.zifangsky.tree.BinaryTreeNode;/** * 求二叉树中叶子节点的个数 * @author Administrator * */public class Question2 {/** * 通过递归前序遍历获取叶子节点个数 * @param root * @return */public int getNumberOfLeavesByPreOrder(BinaryTreeNode root){if(root == null){return 0;}else{if(root.getLeft() == null && root.getRight() == null){ //叶子节点return 1;}else{return getNumberOfLeavesByPreOrder(root.getLeft()) + getNumberOfLeavesByPreOrder(root.getRight());}}}/** * 使用层次遍历获取二叉树叶子节点个数 * * @时间复杂度 O(n) * @param root */public int getNumberOfLeavesByQueue(BinaryTreeNode root){int count = 0; //叶子节点总数LinkQueue queue = new LinkQueue();if(root != null){queue.enQueue(root);}while (!queue.isEmpty()) {BinaryTreeNode temp = (BinaryTreeNode) queue.deQueue();//叶子节点:左孩子节点和右孩子节点都为NULL的节点if(temp.getLeft() == null && temp.getRight() == null){count++;}else{if(temp.getLeft() != null){queue.enQueue(temp.getLeft());}if(temp.getRight() != null){queue.enQueue(temp.getRight());}}}return count;}/** * 测试用例 */@Testpublic void testMethods(){/** * 使用队列构造一个供测试使用的二叉树 * 1 * 2 3 * 4 5 6 7 * 8 9 */LinkQueue queue = new LinkQueue();BinaryTreeNode root = new BinaryTreeNode(1); //根节点queue.enQueue(root);BinaryTreeNode temp = null;for(int i=2;i */public class LinkQueue{private SinglyNode frontNode; //队首节点private SinglyNode rearNode; //队尾节点public LinkQueue() {frontNode = null;rearNode = null;}/** * 返回队列是否为空 * @时间复杂度 O(1) * @return */public boolean isEmpty(){return (frontNode == null);}/** * 返回存储在队列的元素个数 * @时间复杂度 O(n) * @return */public int size(){int length = 0;SinglyNode currentNode = frontNode;while (currentNode != null) {length++;currentNode = currentNode.getNext();}return length;}/** * 入队:在链表表尾插入数据 * @时间复杂度 O(1) * @param data */public void enQueue(K data){SinglyNode newNode = new SinglyNode(data);if(rearNode != null){rearNode.setNext(newNode);}rearNode = newNode;if(frontNode == null){frontNode = rearNode;}}/** * 出队:删除表头节点 * @时间复杂度 O(1) * @return */public Object deQueue(){if(isEmpty()){throw new RuntimeException("Queue Empty!");}else{Object result = frontNode.getData();if(frontNode == rearNode){frontNode = null;rearNode = null;}else{frontNode = frontNode.getNext();}return result;}}}单链表节点SinglyNode的定义:package cn.zifangsky.linkedlist;/** * 单链表的定义 * @author zifangsky * @param */public class SinglyNode {private K data; // 数据private SinglyNode next; // 该节点的下个节点public SinglyNode(K data) {this.data = data;}public SinglyNode(K data, SinglyNode next) {this.data = data;this.next = next;}public K getData() {return data;}public void setData(K data) {this.data = data;}public SinglyNode getNext() {return next;}public void setNext(SinglyNode next) {this.next = next;}@Overridepublic String toString() {return "SinglyNode [data=" + data + "]";}}

2. 用java怎么构造一个二叉树呢

二叉树的相关操作,包括创建,中序、先序、后序(递归和非递归),其中重点的是java在先序创建二叉树和后序非递归遍历的的实现。
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<T> {

private Node<T> root;

public Tree() {
}

public Tree(Node<T> root) {
this.root = root;
}

//创建二叉树
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);
}
//先序遍历创建二叉树
private Node<T> createTree(Node<T> node,Scanner scn) {

String temp = scn.next();

if (temp.trim().equals("#")) {
return null;
} else {
node = new Node<T>((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<T> node) {
if (node != null) {
inOrderTraverse(node.getLeft());
System.out.println(node.getValue());
inOrderTraverse(node.getRight());
}
}

//中序遍历(非递归)
public void nrInOrderTraverse() {

Stack<Node<T>> stack = new Stack<Node<T>>();
Node<T> 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<T> node) {
if (node != null) {
System.out.println(node.getValue());
preOrderTraverse(node.getLeft());
preOrderTraverse(node.getRight());
}
}

//先序遍历(非递归)
public void nrPreOrderTraverse() {

Stack<Node<T>> stack = new Stack<Node<T>>();
Node<T> 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<T> node) {
if (node != null) {
postOrderTraverse(node.getLeft());
postOrderTraverse(node.getRight());
System.out.println(node.getValue());
}
}

//后续遍历(非递归)
public void nrPostOrderTraverse() {

Stack<Node<T>> stack = new Stack<Node<T>>();
Node<T> node = root;
Node<T> preNode = null;//表示最近一次访问的节点

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<T> node) {

Queue<Node<T>> queue = new LinkedBlockingQueue<Node<T>>();
queue.add(node);
while (!queue.isEmpty()) {

Node<T> temp = queue.poll();
if (temp != null) {
System.out.println(temp.getValue());
queue.add(temp.getLeft());
queue.add(temp.getRight());
}

}

}

}

//树的节点

class Node<T> {

private Node<T> left;
private Node<T> right;
private T value;

public Node() {
}
public Node(Node<T> left,Node<T> right,T value) {
this.left = left;
this.right = right;
this.value = value;
}

public Node(T value) {
this(null,null,value);
}
public Node<T> getLeft() {
return left;
}
public void setLeft(Node<T> left) {
this.left = left;
}
public Node<T> getRight() {
return right;
}
public void setRight(Node<T> right) {
this.right = right;
}
public T getValue() {
return value;
}
public void setValue(T value) {
this.value = value;
}

}
测试代码:
package com.algorithm.tree;

public class TreeTest {

/**
* @param args
*/
public static void main(String[] args) {
Tree<Integer> tree = new Tree<Integer>();
tree.buildTree();
System.out.println("中序遍历");
tree.inOrderTraverse();
tree.nrInOrderTraverse();
System.out.println("后续遍历");
//tree.nrPostOrderTraverse();
tree.postOrderTraverse();
tree.nrPostOrderTraverse();
System.out.println("先序遍历");
tree.preOrderTraverse();
tree.nrPreOrderTraverse();

//
}

}

3. 二叉树的应用,用JAVA实现其算法和功能;包手括建立、插入、删除等操作

e

4. 请用java写二叉树算法,实现添加数据形成二叉树功能,并以先序的方式打印出来

推荐你买一本书吧,《数据结构 学习指导与习题解答(Java语言版)》(第二版)john R.Hubbard著,孙燕 陈伊文 译

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

6. 说明生活中遇到的二叉树,用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) );

}

}

看一下吧!这是在网上找的一个例子!看对你有没有帮助!

7. 如何用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

8. 求教,java二叉树节点


迭代使用insert()的方法.下所示为节点node插入树tree中

privateBinaryNode<T>insert(Tnode,BinaryNode<T>tree){
if(node==null)
returntree;

if(tree==null)
returnnewBinaryNode<T>(node,null,null);//第一个null表示左子树为空,
//第二个表示右子树为空

BinaryNode<T>left=tree.left);

if(left==null){
left=newBinaryNode<T>(node,null,null);
}
else
left=insert(node,tree.getLeftNode());

returntree;
}

9. 用JAVA写二叉树

/**
* [Tree2.java] Create on 2008-10-20 下午03:03:24
* Copyright (c) 2008 by iTrusChina.
*/

/**
* @author WangXuanmin
* @version 0.10
*/
public class Tree2Bef {
private StringBuffer bef=new StringBuffer();

//传入中序遍历和后序遍历,返回前序遍历字串
public String getBef(String mid, String beh) {
//若节点存在则向bef中添加该节点,继续查询该节点的左子树和右子树
if (root(mid, beh) != -1) {
int rootindex=root(mid, beh);
char root=mid.charAt(rootindex);
bef.append(root);
System.out.println(bef.toString());
String mleft, mright;
mleft = mid.substring(0,rootindex);
mright = mid.substring(rootindex+1);
getBef(mleft,beh);
getBef(mright,beh);
}
//所有节点查询完毕,返回前序遍历值
return bef.toString();

}

//从中序遍历中根据后序遍历查找节点索引值index
private int root(String mid, String beh) {
char[] midc = mid.toCharArray();
char[] behc = beh.toCharArray();
for (int i = behc.length-1; i > -1; i--) {
for (int j = 0; j < midc.length; j++) {
if (behc[i] == midc[j])
return j;
}
}
return -1;
}

public static void main(String[] args) {
Tree2Bef tree=new Tree2Bef();
String mid="84925163A7B";
String bef="894526AB731";
System.out.println(tree.getBef(mid,bef));
}
}

树结构如图:
1
|-------|
2 3
|---| |---|
4 5 6 7
|-| |-|
8 9 A B

10. 怎么用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); //打印前序
}
}

阅读全文

与用java实现二叉树实现插入相关的资料

热点内容
风月片网站动漫 浏览:765
按摩院电影泰国 浏览:982
沐风之女无删除版百度网盘 浏览:334
女主角叫珍妮的美国电影 浏览:838
庐江电影 浏览:455
电影龙棺命灯免费在线观看 浏览:549
电影吃奶 浏览:690
变形金刚2超清国语版下载 浏览:816
周星驰赌神系列电影 浏览:895
有一部韩国电影老公是废材老婆开了个美容店 浏览:984
恐怖电影在线观看 浏览:697
啄木鸟 电影 浏览:913
xhmb77 浏览:526
男主角叫顾北的小说 浏览:56
免费60帧电影 浏览:389
霸道狠戾总裁肉文 浏览:593
香港古装三及黄色 浏览:897
外国限制级胸大的电影 浏览:313
台湾男男大尺度电影 浏览:308
香港聊斋系列 浏览:802

友情链接