加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

无序数组转化为二叉树或完全二叉树

(2013-07-31 11:32:08)
标签:

数组转化为树

堆排序

二叉树

数据结构

分类: 数据结构

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;


public class UnorderedArrayToTree {

 private int[] An = { 4, 1, 3, 2, 16, 9, 10, 14, 8, 7 }; 
 private static class Tree{
  private Tree parent;
  private Tree leftChild;
  private Tree rightChild;
  private int currentValue;
  public Tree(){}
  public Tree(int data){
   this.parent=null;
   this.leftChild=null;
   this.rightChild=null;
   this.currentValue=data;
  }

 }
 
 public Tree createTree(int An[]){
  Tree root = null;
  List list = new ArrayList();
  int length = An.length;
  for(int i=1;i<=length;i++){
   list.add(new Tree(An[i-1]));
  }
  for(int i=1;i<=list.size()/2-1 && list!=null;i++){
   list.get(i-1).leftChild = list.get(i*2-1);
   list.get(i*2-1).parent = list.get(i-1);
   list.get(i-1).rightChild = list.get(i*2);
   list.get(i*2).parent = list.get(i-1);
  }
  int lastIndex = list.size()/2;
  list.get(lastIndex-1).leftChild=list.get(lastIndex*2-1);
  list.get(lastIndex*2-1).parent = list.get(lastIndex-1);
  if(list.size()%2==1){
   list.get(lastIndex-1).rightChild= list.get(lastIndex*2);
   list.get(lastIndex*2).parent=list.get(lastIndex-1);
  }
  return root = list.get(0);
 }
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有