package com.neu.util;
public class BTNode {
int data;
BTNode left;
BTNode right;
BTNode(){}
BTNode(int val){
data = val;
}
BTNode(int val,BTNode leftChild,BTNode rightChild){
data = val;
left = leftChild;
right = rightChild;
}
public String toString()
{
Integer data1= new Integer(data);
return data1.toString();
}
}
package com.neu.util;
public class BTree {
public BTNode root;//树的根结点
private int count;//树的结点个数
/** Creates a new instance of BTree */
public BTree() {
root = null;
count = 0;
}
public BTNode insert(BTNode ref,int val)//插入建立二叉树
{
if(ref == null){
count++;
return new BTNode(val);
}
else{
if(ref.data>val)
ref.left = insert(ref.left,val);
else
ref.right = insert(ref.right,val);
return ref;
}
}
public void insert(int val)
{
root = insert(root,val);
}
public int size(){
return count;
}
//将二叉树转为按中序排列的一条链
BTNode createChain(BTNode root){
if(root!= null){
root.right = createChain(root.right); //对右子树递归
if(root.left != null){
BTNode oldRoot = root;
BTNode ref = root = createChain(root.left); //对左子树递归,根指向最左结点
oldRoot.left = null;
while(ref.right != null)
ref = ref.right;
ref.right = oldRoot;
}
}
return root;
}
//将链转为平衡二叉树
BTNode createTree(BTNode root,int n){
if(n> 2){
int m = (n-1)/2;
BTNode oldRoot = root;
BTNode ref = root;
for(int i = 1;i<m;i++)
ref = ref.right;
root = ref.right; //指向第[n/2]个结点,即将根指向链的中间结点
ref.right = null; //根的左右结点都置空
root.left = createTree(oldRoot,m);
root.right = createTree(root.right,n-m-1);
}
return root;
}
public String getData() {
if(this.root == null) return "";
Integer n = new Integer(root.data);
return n.toString();
}
public static void inorder(BTNode r){ //中序排列
if(r != null){
inorder(r.left);
System.out.print(r.toString() + " ");
inorder(r.right);
}
}
public void display(){
if(root!=null){
System.out.print("排序:");
inorder(root);
}else{
System.out.println("二叉树为空!");
}
}
public static void main(String[] args){
BTNode node = new BTNode(10);
BTree bt =new BTree();
int arr[]={5,12,20,2,14,1};
for(int i=0;i<arr.length;i++) {
bt.insert(arr[i]);
}
System.out.println();
bt.display();
}
}
Java平衡二叉树
最新推荐文章于 2023-11-27 20:52:27 发布