[JAVA Binary tree,자바알고리즘]이진트리의 노드 수 및 높이를 알려주는 재귀함수 예제, 자바공부 열심히 하세요~ 
//Tree의 노드수 및 높이 Example 
import java.util.*;  //for Random Class 
class BinaryNode    {    
  int  element;                  // The data in 
the node 
  BinaryNode left;          // Left child 
  BinaryNode right;  
      // Right child 
  BinaryNode(int element) { //생성자 
  this( 
element, null, null ); 
  } 
  BinaryNode(int element, BinaryNode left, 
BinaryNode right){ 
            this.element  = element; 
            
this.left    = left; 
            this.right    = right; 
  } 
} 
class BinaryTreeTraversal { 
//트리 생성 
public BinaryNode 
insert(BinaryNode tree, int n) { 
if (tree == null) { 
tree = new 
BinaryNode(n); 
tree.right= tree.left=null; 
} 
else if(n > 
tree.element) { 
tree.right = insert(tree.right, n); 
} 
else { 
tree.left = insert(tree.left, n); 
} 
return tree;  
} 
//Tree의 노드갯수를 return하는 순환알고리즘 
        public int count(BinaryNode 
root) { 
          int num ; 
          if (root == null) { 
      
            num = 0 ; 
          } 
          else { 
                  
num = count(root.left) + count(root.right) + 1; 
          } 
          
return num ; 
        } 
//Tree의 높이를 알려주는 순환알고리즘 
public int 
depth(BinaryNode root) { 
  int dep, depl, depr ; 
  if (root == null) 
{ 
  dep = 0 ; 
  } 
  else { 
  depl = depth(root.left) ; 
  
depr = depth(root.right) ; 
  if (depl >= depr)  
 dep = depl + 1 ; 
  else  
 dep = depr + 1 ; 
  } 
  return dep ; 
}  
} 
public class BinaryTreeTraversalTest { 
public static 
void main(String[] args){ 
BinaryNode root = null; 
int nansu; 
BinaryTreeTraversal tr = new BinaryTreeTraversal();  
Random r = new 
Random(); 
System.out.print("발생된 난수 : " ); 
for(int i=0; i<5; i++) { 
nansu = r.nextInt()%100;                                
System.out.print(nansu + " "); 
//항상 root가 반환된다. 
root = tr.insert(root, 
nansu);  
}

 
 

댓글 없음:
댓글 쓰기