이 진 트 리 의 재 귀 는 이 해 를 실현 한다.

Binary Tree 클래스 의 코드 는 다음 과 같 습 니 다.
http://cslibrary.stanford.edu/110/BinaryTrees.html
중점 이해:
1. 재 귀 방법 을 이해 하고 또 하나의 변화 하 는 재 귀 변 수 를 매개 변수 로 해 야 한다.
2. privateNode insert (Node node, intdata) 함수 가 호출 될 때마다 새로 추 가 된 새 노드 가 아 닌 루트 루트 루트 노드 입 니 다.
3. 이 구현 에서 내부 정적 클래스 의 사용:
1
  p.rivate Node root; 


 private static class Node
     ,      ,   Node        。

2. node 는 간단 한 공장 모델 중의 제품 으로서 추상 적 인 제품, 구체 적 인 제품, 공장 역할 3 자 를 하나 로 합 친 후에 내부 류 로 서 정태 류 로 발전 한다.
 
 private static class Node {

   Node left ; 

   Node right ; 

   int data; 

  

   Node(int newData) {

     left= null;

     right= null;

     data= newData;

   }
 static public Node getNode(int newData) { 
 return new Node(newData);
   }
 }

 
// BinaryTree.java
package study;
 
public class BinaryTree {
 // Root node pointer. Will be null for an empty tree.
 private Node root;
 
 private static class Node {
   Node left ;
   Node right ;
   int data;
 
   Node(int newData) {
     left= null;
     right= null;
     data= newData;
   }
 }
 
 /**
  Createsanempty binarytree -- a nullrootpointer.
 */
 public BinaryTree() {
   root= null;
 }
 
 /**
  Insertsthegiven data into thebinarytree.
  Usesarecursive helper.
 */
 public void insert(intdata) {
   root= insert(root , data);
 }
 
 
 /**
  Recursiveinsert-- given a nodepointer,recurdown and
  insertthegiven data into thetree.Returnsthenew
  nodepointer(thestandardwayto communicate
  achangedpointerbackto the caller).
 */
 private Node insert(Node node,intdata) {
   if(node==null) {
     node =new Node(data);
   }
   else{
     if(data <= node.data) {
       node.left = insert(node.left, data);
     }
     else{
       node.right = insert(node.right, data);
     }
   }
 
   return(node);// in any case, return the new pointer to the caller
 }
 
   
 publicvoid buildTree(int[] data){
    
    for (inti=0;i        insert(data[i]);
     } 
 }
 
 publicvoid printTree() {
     printTree(root );
     System.out .println();
    }
 privatevoid printTree(Node node) {
    if (node ==null)return;
 
    // left, node itself, right
     printTree(node.left );
     System.out .print(node.data+ " " );
     printTree(node.right );
    }
 
 
}

좋은 웹페이지 즐겨찾기