树和二叉树

(认真思考了一下,要学精而不能广而泛之的学习,今天来完成二叉树方面的数据结构组织)

参考书目,数据结构和算法分析(java语言实现)

树可以用几种方法来定义。定义树的一种自然的方式是递归的方式。一棵树是一些节点的集合。这个集合可以是空集;若不是空集,则树由称作根的节点r以及0个或多个非空的子树T1、T2、、、Tk组成,这些子树中每一棵的根都被来自根r的一条有向的边所连接。

几个概念:儿子(child) 父亲(parent) 树叶(leaf)兄弟(siblings)  路径(path)  深度(depth)

树的实现

树节点的声明:

class TreeNode
{
Object element;
TreeNode firstChild;
TreeNode nextSiblings;
}

树的遍历及应用:

(伪代码)

private void listAll(int depth){
printName(depth);// print the name of the object;
if(isDirectory())
for each file c in this directory(for each child)
c.listAll(depth+1);
}

public void listAll()
{
listAll(0);
}

二叉树,一个经典的数据结构,它包含一个指向左子树的指针,一个指向右指数的指针,和一个数据元素

二叉搜索树,在二叉树的基础上,它的左子树的值都小于它,它的右子树的值都大于它

二叉树实现:

class BinaryNode
{
Object element;
BinaryNode left;
BinaryNode right;
}

查找树ADT——二叉查找树

BinaryNode类

private static class BinaryNode<AnyType>
{
BinaryNode(AnyType theElement)
{this(theElement,null,null);}
BinaryNode(AnyType theElement,BinaryNode<AnyType> lt,BinaryNode<AnyType> rt)
{element =theElement;left=lt;right=rt;}
AnyType element;
BinaryNode<AnyType> left;
BinaryNode<AnyType> right;
}

contains方法

如果在树T中存在含有项X的节点,那么这个操作需要返回true,如果这样的节点不存在则返回false

private boolean contains(AnyType x,BinaryNode<AnyType> t)
{
if(t==null)
return false;
int compareResult=x.compareTo(t.element);
if(compareResult<0)
return contains(x,t.left);
else if(compareResult>0)
return contains(x,t.right);
else
return true;
}

findMin方法和 findMax方法

以下两个方法分别返回树中包含最小元和最大元的节点的引用。

private BinaryNode<AnyType> findMax(BinaryNode<AnyType> t)
{
if(t==null)
return null;
else if(t.right==null)
return t;
return findMax(t.right);
}

或者
{
if(t!=null)
   while(t.right!=null)
        t=t.right;

return t;
}

insert方法

将一个X插入进二叉查找树中。

private BinaryNode<AnyType> insert(AnyType x,BinaryNode<AnyType> t)
{
if(t==null)
return new BinaryNode<>(x,null,null);

int compareResult=x.compareTo(t.element);

if(compareResult<0)
t.left=insert(x,t.left);
else if(compareResult >0)
t.right=insert(x,t.right);
else
; do nothing
return t;
}
原文地址:https://www.cnblogs.com/blackiesong/p/6486328.html