java二叉樹遍歷
⑴ 寫一個java層次遍歷二叉樹,簡單點就可以,我要的是代碼,不是純文字說明
public class BinaryNode {
Object element;
BinaryNode left;
BinaryNode right;
}
import java.util.*;
public class Queue {
protected LinkedList list;
// Postcondition: this Queue object has been initialized.
public Queue() {
list = new LinkedList();
} // default constructor
// Postcondition: the number of elements in this Queue object has been
// returned.
public int size() {
return list.size();
} // method size
// Postcondition: true has been returned if this Queue object has no
// elements. Otherwise, false has been returned.
public boolean isEmpty() {
return list.isEmpty();
} // method isEmpty
// Postconditon: A of element has been inserted at the back of this
// Queue object. The averageTime (n) is constant and
// worstTime (n) is O (n).
public void enqueue(Object element) {
list.addLast(element);
} // method enqueue
// Precondition: this Queue object is not empty. Otherwise,
// NoSuchElementException will be thrown.
// Postcondition: The element that was at the front of this Queue object -
// just before this method was called -- has been removed
// from this Queue object and returned.
public Object dequeue() {
return list.removeFirst();
} // method dequeue
// Precondition: this Queue object is not empty. Otherwise,
// NoSuchElementException will be thrown.
// Postcondition: the element at index 0 in this Queue object has been
// returned.
public Object front() {
return list.getFirst();
} // method front
} // Queue class
import java.io.IOException;
public class BinaryTree {
BinaryNode root;
public BinaryTree() {
super();
// TODO 自動生成構造函數存根
root=this.createPre();
}
public BinaryNode createPre()
//按照先序遍歷的輸入方法,建立二叉樹
{
BinaryNode t=null;
char ch;
try {
ch = (char)System.in.read();
if(ch==' ')
t=null;
else
{
t=new BinaryNode();
t.element=(Object)ch;
t.left=createPre();
t.right=createPre();
}
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
return t;
}
public void inOrder()
{
this.inOrder(root);
}
public void inOrder(BinaryNode t)
//中序遍歷二叉樹
{
if(t!=null)
{
inOrder(t.left);
System.out.print(t.element);
inOrder(t.right);
}
}
public void postOrder()
{
this.postOrder(root);
}
public void postOrder(BinaryNode t)
//後序遍歷二叉樹
{
if(t!=null)
{
postOrder(t.left);
System.out.print(t.element);
postOrder(t.right);
}
}
public void preOrder()
{
this.preOrder(root);
}
public void preOrder(BinaryNode t)
//前序遍歷二叉樹
{
if(t!=null)
{
System.out.print(t.element);
preOrder(t.left);
preOrder(t.right);
}
}
public void breadthFirst()
{
Queue treeQueue=new Queue();
BinaryNode p;
if(root!=null)
treeQueue.enqueue(root);
while(!treeQueue.isEmpty())
{
System.out.print(((BinaryNode)(treeQueue.front())).element);
p=(BinaryNode)treeQueue.dequeue();
if(p.left!=null)
treeQueue.enqueue(p.left);
if(p.right!=null)
treeQueue.enqueue(p.right);
}
}
}
public class BinaryTreeTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO 自動生成方法存根
BinaryTree tree = new BinaryTree();
System.out.println("先序遍歷:");
tree.preOrder();
System.out.println();
System.out.println("中序遍歷:");
tree.inOrder();
System.out.println();
System.out.println("後序遍歷:");
tree.postOrder();
System.out.println();
System.out.println("層次遍歷:");
tree.breadthFirst();
System.out.println();
}
}
⑵ 二叉樹的java實現與幾種遍歷
二叉樹的定義
二叉樹(binary tree)是結點的有限集合,這個集合或者空,或者由一個根及兩個互不相交的稱為這個根的左子樹或右子樹構成.
從定義可以看出,二叉樹包括:1.空樹 2.只有一個根節點 3.只有左子樹 4.只有右子樹 5.左右子樹都存在 有且僅有這5種表現形式
二叉樹的遍歷分為三種:前序遍歷 中序遍歷 後序遍歷
前序遍歷:按照「根左右」,先遍歷根節點,再遍歷左子樹 ,再遍歷右子樹
中序遍歷:按照「左根右「,先遍歷左子樹,再遍歷根節點,最後遍歷右子樹
後續遍歷:按照「左右根」,先遍歷左子樹,再遍歷右子樹,最後遍歷根節點
其中前,後,中指的是每次遍歷時候的根節點被遍歷的順序
具體實現看下圖:
⑶ java實現二叉樹的問題
/**
* 二叉樹測試二叉樹順序存儲在treeLine中,遞歸前序創建二叉樹。另外還有能
* 夠前序、中序、後序、按層遍歷二叉樹的方法以及一個返回遍歷結果asString的
* 方法。
*/
public class BitTree {
public static Node2 root;
public static String asString;
//事先存入的數組,符號#表示二叉樹結束。
public static final char[] treeLine = {'a','b','c','d','e','f','g',' ',' ','j',' ',' ','i','#'};
//用於標志二叉樹節點在數組中的存儲位置,以便在創建二叉樹時能夠找到節點對應的數據。
static int index;
//構造函數
public BitTree() {
System.out.print("測試二叉樹的順序表示為:");
System.out.println(treeLine);
this.index = 0;
root = this.setup(root);
}
//創建二叉樹的遞歸程序
private Node2 setup(Node2 current) {
if (index >= treeLine.length) return current;
if (treeLine[index] == '#') return current;
if (treeLine[index] == ' ') return current;
current = new Node2(treeLine[index]);
index = index * 2 + 1;
current.left = setup(current.left);
index ++;
current.right = setup(current.right);
index = index / 2 - 1;
return current;
}
//二叉樹是否為空。
public boolean isEmpty() {
if (root == null) return true;
return false;
}
//返回遍歷二叉樹所得到的字元串。
public String toString(int type) {
if (type == 0) {
asString = "前序遍歷:\t";
this.front(root);
}
if (type == 1) {
asString = "中序遍歷:\t";
this.middle(root);
}
if (type == 2) {
asString = "後序遍歷:\t";
this.rear(root);
}
if (type == 3) {
asString = "按層遍歷:\t";
this.level(root);
}
return asString;
}
//前序遍歷二叉樹的循環演算法,每到一個結點先輸出,再壓棧,然後訪問它的左子樹,
//出棧,訪問其右子樹,然後該次循環結束。
private void front(Node2 current) {
StackL stack = new StackL((Object)current);
do {
if (current == null) {
current = (Node2)stack.pop();
current = current.right;
} else {
asString += current.ch;
current = current.left;
}
if (!(current == null)) stack.push((Object)current);
} while (!(stack.isEmpty()));
}
//中序遍歷二叉樹
private void middle(Node2 current) {
if (current == null) return;
middle(current.left);
asString += current.ch;
middle(current.right);
}
//後序遍歷二叉樹的遞歸演算法
private void rear(Node2 current) {
if (current == null) return;
rear(current.left);
rear(current.right);
asString += current.ch;
}
}
/**
* 二叉樹所使用的節點類。包括一個值域兩個鏈域
*/
public class Node2 {
char ch;
Node2 left;
Node2 right;
//構造函數
public Node2(char c) {
this.ch = c;
this.left = null;
this.right = null;
}
//設置節點的值
public void setChar(char c) {
this.ch = c;
}
//返回節點的值
public char getChar() {
return ch;
}
//設置節點的左孩子
public void setLeft(Node2 left) {
this.left = left;
}
//設置節點的右孩子
public void setRight (Node2 right) {
this.right = right;
}
//如果是葉節點返回true
public boolean isLeaf() {
if ((this.left == null) && (this.right == null)) return true;
return false;
}
}
一個作業題,裡面有你要的東西。
主函數自己寫吧。當然其它地方也有要改的。
⑷ 怎樣使用java對二叉樹進行層次遍歷
publicclassBinaryTree{
intdata;//根節點數據
BinaryTreeleft;//左子樹
BinaryTreeright;//右子樹
publicBinaryTree(intdata)//實例化二叉樹類
{
this.data=data;
left=null;
right=null;
}
publicvoidinsert(BinaryTreeroot,intdata){//向二叉樹中插入子節點
if(data>root.data)//二叉樹的左節點都比根節點小
{
if(root.right==null){
root.right=newBinaryTree(data);
}else{
this.insert(root.right,data);
}
}else{//二叉樹的右節點都比根節點大
if(root.left==null){
root.left=newBinaryTree(data);
}else{
this.insert(root.left,data);
}
}
}
}
當建立好二叉樹類後可以創建二叉樹實例,並實現二叉樹的先根遍歷,中根遍歷,後根遍歷,代碼如下:
packagepackage2;
publicclassBinaryTreePreorder{
publicstaticvoidpreOrder(BinaryTreeroot){//先根遍歷
if(root!=null){
System.out.print(root.data+"-");
preOrder(root.left);
preOrder(root.right);
}
}
publicstaticvoidinOrder(BinaryTreeroot){//中根遍歷
if(root!=null){
inOrder(root.left);
System.out.print(root.data+"--");
inOrder(root.right);
}
}
publicstaticvoidpostOrder(BinaryTreeroot){//後根遍歷
if(root!=null){
postOrder(root.left);
postOrder(root.right);
System.out.print(root.data+"---");
}
}
publicstaticvoidmain(String[]str){
int[]array={12,76,35,22,16,48,90,46,9,40};
BinaryTreeroot=newBinaryTree(array[0]);//創建二叉樹
for(inti=1;i<array.length;i++){
root.insert(root,array[i]);//向二叉樹中插入數據
}
System.out.println("先根遍歷:");
preOrder(root);
System.out.println();
System.out.println("中根遍歷:");
inOrder(root);
System.out.println();
System.out.println("後根遍歷:");
postOrder(root);
⑸ 什麼是樹的遍歷java
樹遍歷方法:有先序遍歷、中序遍歷、後序遍歷以及廣度優先遍歷四種遍歷樹的方法
Demo:
publicclassThreeLinkBinTree<E>{
publicstaticclassTreeNode{
Objectdata;
TreeNodeleft;
TreeNoderight;
TreeNodeparent;
publicTreeNode(){
}
publicTreeNode(Objectdata){
this.data=data;
}
publicTreeNode(Objectdata,TreeNodeleft,TreeNoderight,TreeNodeparent){
this.data=data;
this.left=left;
this.right=right;
this.parent=parent;
}
}
privateTreeNoderoot;
//以默認的構造器創建二叉樹
publicThreeLinkBinTree(){
this.root=newTreeNode();
}
//以指定根元素創建二叉樹
publicThreeLinkBinTree(Edata){
this.root=newTreeNode(data);
}
/**
*為指定節點添加子節點
*
*@paramparent需要添加子節點的父節點的索引
*@paramdata新子節點的數據
*@paramisLeft是否為左節點
*@return新增的節點
*/
publicTreeNodeaddNode(TreeNodeparent,Edata,booleanisLeft){
if(parent==null){
thrownewRuntimeException(parent+"節點為null,無法添加子節點");
}
if(isLeft&&parent.left!=null){
thrownewRuntimeException(parent+"節點已有左子節點,無法添加左子節點");
}
if(!isLeft&&parent.right!=null){
thrownewRuntimeException(parent+"節點已有右子節點,無法添加右子節點");
}
TreeNodenewNode=newTreeNode(data);
if(isLeft){
//讓父節點的left引用指向新節點
parent.left=newNode;
}else{
//讓父節點的left引用指向新節點
parent.right=newNode;
}
//讓新節點的parent引用到parent節點
newNode.parent=parent;
returnnewNode;
}
//判斷二叉樹是否為空
publicbooleanempty(){
//根據元素判斷二叉樹是否為空
returnroot.data==null;
}
//返回根節點
publicTreeNoderoot(){
if(empty()){
thrownewRuntimeException("樹為空,無法訪問根節點");
}
returnroot;
}
//返回指定節點(非根節點)的父節點
publicEparent(TreeNodenode){
if(node==null){
thrownewRuntimeException("節點為null,無法訪問其父節點");
}
return(E)node.parent.data;
}
//返回指定節點(非葉子)的左子節點,當左子節點不存在時返回null
publicEleftChild(TreeNodeparent){
if(parent==null){
thrownewRuntimeException(parent+"節點為null,無法添加子節點");
}
returnparent.left==null?null:(E)parent.left.data;
}
//返回指定節點(非葉子)的右子節點,當右子節點不存在時返回null
publicErightChild(TreeNodeparent){
if(parent==null){
thrownewRuntimeException(parent+"節點為null,無法添加子節點");
}
returnparent.right==null?null:(E)parent.right.data;
}
//返回該二叉樹的深度
publicintdeep(){
//獲取該樹的深度
returndeep(root);
}
//這是一個遞歸方法:每一棵子樹的深度為其所有子樹的最大深度+1
privateintdeep(TreeNodenode){
if(node==null){
return0;
}
//沒有子樹
if(node.left==null&&node.right==null){
return1;
}else{
intleftDeep=deep(node.left);
intrightDeep=deep(node.right);
//記錄其所有左、右子樹中較大的深度
intmax=leftDeep>rightDeep?leftDeep:rightDeep;
//返回其左右子樹中較大的深度+1
returnmax+1;
}
}
//實現先序遍歷
//1、訪問根節點
//2、遞歸遍歷左子樹
//3、遞歸遍歷右子樹
publicList<TreeNode>preIterator(){
returnpreIterator(root);
}
privateList<TreeNode>preIterator(TreeNodenode){
List<TreeNode>list=newArrayList<TreeNode>();
//處理根節點
list.add(node);
//遞歸處理左子樹
if(node.left!=null){
list.addAll(preIterator(node.left));
}
//遞歸處理右子樹
if(node.right!=null){
list.addAll(preIterator(node.right));
}
returnlist;
}
//實現中序遍歷
//1、遞歸遍歷左子樹
//2、訪問根節點
//3、遞歸遍歷右子樹
publicList<TreeNode>inIterator(){
returninIterator(root);
}
privateList<TreeNode>inIterator(TreeNodenode){
List<TreeNode>list=newArrayList<TreeNode>();
//遞歸處理左子樹
if(node.left!=null){
list.addAll(inIterator(node.left));
}
//處理根節點
list.add(node);
//遞歸處理右子樹
if(node.right!=null){
list.addAll(inIterator(node.right));
}
returnlist;
}
//實現後序遍歷
//1、遞歸遍歷左子樹
//2、遞歸遍歷右子樹
//3、訪問根節點
publicList<TreeNode>postIterator(){
returnpostIterator(root);
}
privateList<TreeNode>postIterator(TreeNodenode){
List<TreeNode>list=newArrayList<TreeNode>();
//遞歸處理左子樹
if(node.left!=null){
list.addAll(postIterator(node.left));
}
//遞歸處理右子樹
if(node.right!=null){
list.addAll(postIterator(node.right));
}
//處理根節點
list.add(node);
returnlist;
}
//實現廣度優先遍歷
//廣度優先遍歷又稱為按層遍歷,整個遍歷演算法先遍歷二叉樹的第一層(根節點),再遍歷根節點的兩個子節點(第二層),以此類推
publicList<TreeNode>breadthFirst(){
Queue<TreeNode>queue=newArrayDeque<TreeNode>();
List<TreeNode>list=newArrayList<TreeNode>();
if(root!=null){
//將根元素加入「隊列」
queue.offer(root);
}
while(!queue.isEmpty()){
//將該隊列的「隊尾」的元素添加到List中
list.add(queue.peek());
TreeNodep=queue.poll();
//如果左子節點不為null,將它加入「隊列」
if(p.left!=null){
queue.offer(p.left);
}
//如果右子節點不為null,將它加入「隊列」
if(p.right!=null){
queue.offer(p.right);
}
}
returnlist;
}
}
⑹ java二叉樹遍歷問題
二叉樹具有以下重要性質:
性質1 二叉樹第i層上的結點數目最多為2i-1(i≥1)。
證明:用數學歸納法證明:
歸納基礎:i=1時,有2i-1=20=1。因為第1層上只有一個根結點,所以命題成立。
歸納假設:假設對所有的j(1≤j<i)命題成立,即第j層上至多有2j-1個結點,證明j=i時命題亦成立。
歸納步驟:根據歸納假設,第i-1層上至多有2i-2個結點。由於二叉樹的每個結點至多有兩個孩子,故第i層上的結點數至多是第i-1層上的最大結點數的2倍。即j=i時,該層上至多有2×2i-2=2i-1個結點,故命題成立。
性質2 深度為k的二叉樹至多有2k-1個結點(k≥1)。
證明:在具有相同深度的二叉樹中,僅當每一層都含有最大結點數時,其樹中結點數最多。因此利用性質1可得,深度為k的二叉樹的結點數至多為:
20+21+…+2k-1=2k-1
故命題正確。
性質3 在任意-棵二叉樹中,若終端結點的個數為n0,度為2的結點數為n2,則no=n2+1。
證明:因為二叉樹中所有結點的度數均不大於2,所以結點總數(記為n)應等於0度結點數、1度結點(記為n1)和2度結點數之和:
n=no+n1+n2 (式子1)
另一方面,1度結點有一個孩子,2度結點有兩個孩子,故二叉樹中孩子結點總數是:
nl+2n2
樹中只有根結點不是任何結點的孩子,故二叉樹中的結點總數又可表示為:
n=n1+2n2+1 (式子2)
由式子1和式子2得到:
no=n2+1
滿二叉樹和完全二叉樹是二叉樹的兩種特殊情形。
1、滿二叉樹(FullBinaryTree)
一棵深度為k且有2k-1個結點的二又樹稱為滿二叉樹。
滿二叉樹的特點:
(1) 每一層上的結點數都達到最大值。即對給定的高度,它是具有最多結點數的二叉樹。
(2) 滿二叉樹中不存在度數為1的結點,每個分支結點均有兩棵高度相同的子樹,且樹葉都在最下一層上。
圖(a)是一個深度為4的滿二叉樹。
2、完全二叉樹(Complete BinaryTree)
若一棵二叉樹至多隻有最下面的兩層上結點的度數可以小於2,並且最下一層上的結點都集中在該層最左邊的若干位置上,則此二叉樹稱為完全二叉樹。
特點:
(1) 滿二叉樹是完全二叉樹,完全二叉樹不一定是滿二叉樹。
(2) 在滿二叉樹的最下一層上,從最右邊開始連續刪去若干結點後得到的二叉樹仍然是一棵完全二叉樹。
(3) 在完全二叉樹中,若某個結點沒有左孩子,則它一定沒有右孩子,即該結點必是葉結點。
如圖(c)中,結點F沒有左孩子而有右孩子L,故它不是一棵完全二叉樹。
圖(b)是一棵完全二叉樹。
性質4 具有n個結點的完全二叉樹的深度為
證明:設所求完全二叉樹的深度為k。由完全二叉樹定義可得:
深度為k得完全二叉樹的前k-1層是深度為k-1的滿二叉樹,一共有2k-1-1個結點。
由於完全二叉樹深度為k,故第k層上還有若干個結點,因此該完全二叉樹的結點個數:
n>2k-1-1。
另一方面,由性質2可得:
n≤2k-1,
即:2k-1-l<n≤2k-1
由此可推出:2k-1≤n<2k,取對數後有:
k-1≤lgn<k
又因k-1和k是相鄰的兩個整數,故有
,
由此即得:
注意:
的證明
⑺ 用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();
}
}
⑻ java 實現二叉樹的層次遍歷
class TreeNode {
public TreeNode left;
public TreeNode right;
public int value;
public TreeNode(TreeNode left, TreeNode right, int value) {
this.left = left;
this.right = right;
this.value = value;
}
}
public class BinaryTree {
public static int getTreeHeight(TreeNode root) {
if (root == null)
return 0;
if (root.left == null && root.right == null)
return 1;
return 1 + Math
.max(getTreeHeight(root.left), getTreeHeight(root.right));
}
public static void recursePreOrder(TreeNode root) {
if (root == null)
return;
System.out.println(root.value);
if (root.left != null)
recursePreOrder(root.left);
if (root.right != null)
recursePreOrder(root.right);
}
public static void stackPreOrder(TreeNode root) {
Stack stack = new Stack();
if (root == null)
return;
stack.push(root);
System.out.println(root.value);
TreeNode temp = root.left;
while (temp != null) {
stack.push(temp);
System.out.println(temp.value);
temp = temp.left;
}
temp = (TreeNode) stack.pop();
while (temp != null) {
temp = temp.right;
while (temp != null) {
stack.push(temp);
System.out.println(temp.value);
temp = temp.left;
}
if (stack.empty())
break;
temp = (TreeNode) stack.pop();
}
}
public static void recurseInOrder(TreeNode root) {
if (root == null)
return;
if (root.left != null)
recurseInOrder(root.left);
System.out.println(root.value);
if (root.right != null)
recurseInOrder(root.right);
}
public static void stackInOrder(TreeNode root) {
Stack stack = new Stack();
if (root == null)
return;
else
stack.push(root);
TreeNode temp = root.left;
while (temp != null) {
stack.push(temp);
temp = temp.left;
}
temp = (TreeNode) stack.pop();
while (temp != null) {
System.out.println(temp.value);
temp = temp.right;
while (temp != null) {
stack.push(temp);
temp = temp.left;
}
if (stack.empty())
break;
temp = (TreeNode) stack.pop();
}
}
public static void main(String[] args) {
TreeNode node1 = new TreeNode(null, null, 1);
TreeNode node2 = new TreeNode(null, node1, 2);
TreeNode node3 = new TreeNode(null, null, 3);
TreeNode node4 = new TreeNode(node2, node3, 4);
TreeNode node5 = new TreeNode(null, null, 5);
TreeNode root = new TreeNode(node4, node5, 0);
System.out.println("Tree Height is " + getTreeHeight(root));
System.out.println("Recurse In Order Traverse");
recurseInOrder(root);
System.out.println("Stack In Order Traverse");
stackInOrder(root);
System.out.println("Recurse Pre Order Traverse");
recursePreOrder(root);
System.out.println("Stack Pre Order Traverse");
stackPreOrder(root);
}
}
可以做個參考
⑼ java實現二叉樹層次遍歷
import java.util.ArrayList;
public class TreeNode {
private TreeNode leftNode;
private TreeNode rightNode;
private String nodeName;
public TreeNode getLeftNode() {
return leftNode;
}
public void setLeftNode(TreeNode leftNode) {
this.leftNode = leftNode;
}
public TreeNode getRightNode() {
return rightNode;
}
public void setRightNode(TreeNode rightNode) {
this.rightNode = rightNode;
}
public String getNodeName() {
return nodeName;
}
public void setNodeName(String nodeName) {
this.nodeName = nodeName;
}
public static int level=0;
public static void findNodeByLevel(ArrayList<TreeNode> nodes){
if(nodes==null||nodes.size()==0){
return ;
}
level++;
ArrayList<TreeNode> temp = new ArrayList();
for(TreeNode node:nodes){
System.out.println("第"+level+"層:"+node.getNodeName());
if(node.getLeftNode()!=null){
temp.add(node.getLeftNode());
}
if(node.getRightNode()!=null){
temp.add(node.getRightNode());
}
}
nodes.removeAll(nodes);
findNodeByLevel(temp);
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeNode root = new TreeNode();
root.setNodeName("root");
TreeNode node1 = new TreeNode();
node1.setNodeName("node1");
TreeNode node3 = new TreeNode();
node3.setNodeName("node3");
TreeNode node7 = new TreeNode();
node7.setNodeName("node7");
TreeNode node8 = new TreeNode();
node8.setNodeName("node8");
TreeNode node4 = new TreeNode();
node4.setNodeName("node4");
TreeNode node2 = new TreeNode();
node2.setNodeName("node2");
TreeNode node5 = new TreeNode();
node5.setNodeName("node5");
TreeNode node6 = new TreeNode();
node6.setNodeName("node6");
root.setLeftNode(node1);
node1.setLeftNode(node3);
node3.setLeftNode(node7);
node3.setRightNode(node8);
node1.setRightNode(node4);
root.setRightNode(node2);
node2.setLeftNode(node5);
node2.setRightNode(node6);
ArrayList<TreeNode> nodes = new ArrayList<TreeNode>();
nodes.add(root);
findNodeByLevel(nodes);
}
}
⑽ Java 語言中 二叉樹的遍歷
public class BinaryTreeTest
{
public static void main(String args[])
{
BinaryTreeTest b=new BinaryTreeTest();
int data[]={12,11,34,45,67,89,56,43,22,98};
BinaryTree root =new BinaryTree(data[0]); System.out.print("二叉樹的中的數據:");
for(int i=1;i{
root.insertTree(root,data[i]);
System.out.print(data[i-1]+";");
} System.out.println(data[data.length-1]); int key=Integer.parseInt(args[0]); if(b.searchkey(root,key))
{
System.out.println("找到了:"+key);
}
else
{
System.out.println("沒有找到:"+key);
}
} public boolean searchkey(BinaryTree root, int key)
{
boolean bl=false;
if(root==null)
{
bl=false;
return bl;
}
else if(root.data==key)
{
bl=true;
return bl;
}
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;
} public void insertTree(BinaryTree root, int data)
{
if(data>=root.data)
{
if(root.rightpoiter==null)
{
root.rightpoiter=new BinaryTree(data);
}
else
{
insertTree(root.rightpoiter,data);
}
}
else
{
if(root.leftpoiter==null)
{
root.leftpoiter=new BinaryTree(data);
}
else
{
insertTree(root.leftpoiter,data);
}
}
}
}