導航:首頁 > 編程語言 > 用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實現二叉樹實現插入相關的資料

熱點內容
F中文電影站 瀏覽:990
從深圳往香港寄文件快遞多少錢 瀏覽:157
有一部小說兩姐妹女主姓蘇 瀏覽:878
在哪裡能看香腸派對數據 瀏覽:674
工控軟體編程是什麼 瀏覽:528
三個棒球少年與媽媽們百度雲 瀏覽:659
北京java講師 瀏覽:432
薄帝集團八本順序 瀏覽:220
蘋果7用升級嗎 瀏覽:826
大多多電影網台灣倫理片 瀏覽:473
小米8分類文件找不到 瀏覽:667
國外電影中的女惡魔 瀏覽:808
找不到文件 瀏覽:656
女人的戰爭之消失的眼角膜電影 瀏覽:694
東南亞四級片介紹 瀏覽:959
道士強奸僵屍 瀏覽:541
含糖1v1荔枝筆趣閣 瀏覽:761
app有什麼免費的電影 瀏覽:523
龍棺命燈 瀏覽:221
win7關機自動關閉程序 瀏覽:918

友情鏈接