이 기사에서는 Java가 구현 한 이진 트리의 일반적인 작업에 대해 설명합니다. 다음과 같이 참조에 대해 공유하십시오.
import java.util.arraydeque; import java.util.queue; import java.util.stack; // 이진 트리 생성, 재귀 비 재구성 트래버스 계층 시퀀스 트래버스 전면, 중간 및 뒤에서 // 노드 클래스 node {int 요소; 노드 왼쪽; 노드 오른쪽; public node () {} public node (int element) {this.element = element; }} // BinaryTreePublic Class Tree {// 배열 공개 정적 노드 CreattRee (int [] data, int i) {if (i> = data.length || data [i] == -1) return null; 노드 온도 = 새 노드 (데이터 [i]); temp.left = Creattree (data, i * 2 + 1); Temp.right = CreattRee (데이터, i * 2 + 2); 반환 온도; } // 사전 사전 주문 트래버스 재귀 공개 정적 무효 사전 (노드 온도) {if (temp == null) return; System.out.print (Temp.Element + ""); pre (temp.left); pre (temp.right); } // 미드 주문 트래버스 재귀 적 공개 정적 무효 미드 (노드 온도) {if (temp == null) return; 중간 (temp.left); System.out.print (Temp.Element + ""); 중간 (Temp.right); } // 마지막 포스트 주문 트래버스 재귀 공개 정적 무효 연주 (노드 온도) {if (temp == null) return; 마지막 (temp.left); 마지막 (Temp.right); System.out.print (Temp.Element + ""); } // pre1 pre-1 선주문 트래버스 비 회수 대중 정적 무효 pre1 (노드 온도) {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의 비거인 중의 순차적 트래버스는 비수체적인 공개 정적 void mid1 (노드 온도) {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 + ""); 온도; }}} // 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.right; } if (! stack.isempty ()) {temp = stack.pop (). 왼쪽; }} while (! stack2.isempty ()) system.out.print (stack2.pop (). element + ""); } // CENG 레이어 시퀀스 트래버스 공개 정적 무효 CENG (노드 온도) {if (temp == null) return; 큐 <노드> 큐 = New ArrayDeque <> (); queue.offer (온도); 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); }} // 데모 공개 정적 무효 메인 (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 테스트 결과 :"); 사전 (나무); System.out.println (); pre1 (트리); System.out.println (); 중간 (나무); System.out.println (); Mid1 (나무); System.out.println (); Mid1 (나무); System.out.println (); 마지막 (나무); System.out.println (); last1 (나무); System.out.println (); Ceng (나무); }}실행 결과 :
Java 알고리즘에 대한 자세한 내용은이 사이트에 관심이있는 독자들이 주제를 볼 수 있습니다. "Java 데이터 구조 및 알고리즘 자습서", "Java Operation Dom Node Tips 요약", "Java 파일 및 디렉토리 작동 팁 요약"및 "Java Cache Operation Tips의 요약"을 볼 수 있습니다.
이 기사가 모든 사람의 Java 프로그래밍에 도움이되기를 바랍니다.