排序二叉树
/**较高的查找效率,而且是链式存储,易插入删除*/
public class BinarySortTree
{
/**
*根节点
*/
public var treeRoot:Node;
public function BinarySortTree(_root:Node = null)
{
if (_root){
treeRoot = _root;
}
}
/**
*插入数组
*/
public function insert(arr:Array):void{
for each(var item:int in arr){
insertItem(item);
}
}
/**
*插入单个元素
*/
public function insertItem(item:int):void{
if(treeRoot){
var tempTree:BinarySortTree;
if (item < treeRoot.value){
tempTree = new BinarySortTree(treeRoot.left);
tempTree.insertItem(item);
if(!treeRoot.left){
this.treeRoot.left = tempTree.treeRoot;
}
}else{
tempTree = new BinarySortTree(treeRoot.right);
tempTree.insertItem(item);
if(!treeRoot.right){
this.treeRoot.right = tempTree.treeRoot;
}
}
}else{
this.treeRoot = new Node(item);
}
}
/**
*中序遍历所有节点 ,得到从小到大序列
*/
public function printAllNodes():void{
if(treeRoot){
var tempTree:BinarySortTree;
tempTree = new BinarySortTree(treeRoot.left);
tempTree.printAllNodes();
trace(treeRoot.value);
tempTree = new BinarySortTree(treeRoot.right);
tempTree.printAllNodes();
}
}
}
}
class Node
{
public var value:int;
public var left:Node;
public var right:Node;
public function Node(value:int)
{
this.value = value;
}
}
=============================
/**演示*/
public function Main()
{
var tree:BinarySortTree = new BinarySortTree;
tree.insert([2,4,3,5,7,11,9,22,1]);
tree.printAllNodes();
}