この記事では、Javaが実装したバイナリツリーの一般的な操作について説明します。次のように、参照のために共有してください。
Import java.util.arraydeque; Import java.util.queue; Import java.util.stack; //バイナリツリーの作成、再帰的非再帰的トラバーサル階層シーケンストラバーサルは、中央、および背面、//ノードノードクラスノード{int element;左ノード。ノード右; public node(){} public node(int element){this.element = element; }} // BinaryTreepublic Class Tree {//配列からツリーを作成しますpublic static node creattree(int [] data、int i){if(i> = data.length || data [i] == -1)return null;ノードtemp = new Node(data [i]); temp.left = creattree(data、i * 2 + 1); temp.right = creattree(data、i * 2 + 2); return temp; } //事前予約注文トラバーサル再帰再帰再帰パブリック静止void pre(node temp){if(temp == null)return; System.out.print(temp.Element + ""); pre(temp.Left); pre(temp.right); } //中期トラバーサル再帰再帰パブリック静的ボイドMID(ノード温度){if(temp == null)return; MID(TEMP.LEFT); System.out.print(temp.Element + ""); MID(temp.right); } //最後の順序張りのトラバーサル再帰再帰パブリック静的ボイドlast(node temp){if(temp == null)return; last(temp.Left); last(temp.right); System.out.print(temp.Element + ""); } // PRE1予約注文トラバーサル非再帰的なパブリック静的ボイドpre1(node temp){stack <node> stack = new stack <>(); while(temp!= null ||!stack.isempty()){while(temp!= null){stack.push(temp); System.out.print(temp.Element + ""); temp = temp.left; } if(!stack.isempty()){temp = stack.pop()。右; }}} //中mid1の非再帰的public static void mid1(node temp){stack <node> stack = new stack <>(); while(temp!= null ||!stack.isempty()){while(temp!= null){stack.push(temp); temp = temp.left; } if(!stack.isempty()){temp = stack.pop(); System.out.print(temp.Element + ""); Temp.right; }}} // last1順序の順序トラバーサル非再帰的なパブリック静的void last1(node temp){stack <node> stack = new stack <>(); stack <node> stack2 = new stack <>(); while(temp!= null ||!stack.isempty()){while(temp!= null){stack.push(temp); stack2.push(temp); temp = temp.right; } if(!stack.isempty()){temp = stack.pop()。左; }} while(!stack2.isempty())system.out.print(stack2.pop()。要素 + ""); } // ceng層シーケンストラバーサルpublic static void ceng(node temp){if(temp == null)return; queue <node> queue = new arraydeque <>(); queue.offer(temp); while(!queue.isempty()){temp = queue.poll(); System.out.print(temp.Element + ""); if(temp.left!= null)queue.offer(temp.left); if(temp.right!= null)queue.offer(temp.right); }} //デモpublic static void main(string [] args){int [] array = {1、2、3、4、5、6、7、-1、-1、10、-1、-1、13};ノードツリー= creattree(array、0); system.out.println( "wulin.comテスト結果:"); pre(tree); System.out.println(); pre1(ツリー); System.out.println(); Mid(tree); System.out.println(); Mid1(ツリー); System.out.println(); Mid1(ツリー); System.out.println(); last(tree); System.out.println(); last1(tree); System.out.println(); CENG(ツリー); }}実行結果:
Javaアルゴリズムの詳細については、このサイトに興味のある読者は、「Javaデータ構造とアルゴリズムのチュートリアル」、「Java操作DOMノードのヒントの要約」、「Javaファイルの要約およびディレクトリ操作のヒント」、「Java Cache操作のヒントの要約」というトピックを見ることができます。
この記事がみんなのJavaプログラミングに役立つことを願っています。