在JAVA中實現的二叉樹結構

來源:互聯網
上載者:User

最近研究了一下二叉樹結構,參考了一些資料,總結了一下。

package com.test;
/** *//**
*
* 在JAVA中實現二叉樹結構
*
* 講解:
* 二個方法函數,一個尋找關鍵字--searchkey 另一個是插入一個結點:insertTree
*
* 另外這是一個完全的先序遍曆二叉樹的文法。先根結點,再左結點,如無再右結點,如些加歸至
*
* 搜尋完畢。
*
*/
public class BinaryTreeTest ...{
private BinaryTree root = null;
public BinaryTreeTest() ...{
init();
}
/** *//**
* 初始化給定資料的二叉樹結構
*
*/
private void init() ...{
int data[] = ...{ 12, 11, 34, 45, 67, 38, 56, 43, 22, 8 };
root = new BinaryTree(data[0]);
System.out.println("二叉樹的中的資料結構:");
System.out.println("------------------------------------");
System.out.println(data[0] + ":root");
for (int i = 1; i < data.length; i++) ...{
System.out.print(data[i] + ":");
root.insertTree(root, data[i]);
}
System.out.println("------------------------------------");
}
public void serach(int key) ...{
if (searchkey(root, key)) ...{
System.out.println("找到了:" + key);
} else ...{
System.out.println("沒有找到:" + key);
}
}
private boolean searchkey(BinaryTree root, int key) ...{
if (root == null) ...{
return false;
} else if (root.data == key) ...{
return true;
} else if (key >= root.data) ...{
return searchkey(root.rightpoiter, key);
}
return searchkey(root.leftpoiter, key);
}
class BinaryTree ...{
int data;
BinaryTree leftpoiter;
BinaryTree rightpoiter;
BinaryTree(int data) ...{
this.data = data;
leftpoiter = null;
rightpoiter = null;
}
private void insertTree(BinaryTree root, int data) ...{
if (data >= root.data) ...{
if (root.rightpoiter == null) ...{
System.out.println(" -> new rightpoiter");
root.rightpoiter = new BinaryTree(data);
} else ...{
System.out.print(" -> rightpoiter");
insertTree(root.rightpoiter, data);
}
} else ...{
if (root.leftpoiter == null) ...{
System.out.println(" -> new leftpoiter");
root.leftpoiter = new BinaryTree(data);
} else ...{
System.out.print(" -> leftpoiter");
insertTree(root.leftpoiter, data);
}
}
}
}
public static void main(String args[]) ...{
BinaryTreeTest b = new BinaryTreeTest();
int key = 8; //key:任意數值
b.serach(key); //到二叉樹中尋找
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.