您的位置:首页 > 其它

二叉树

2015-06-11 15:54 309 查看
二叉树,是一颗树,其中每个节点都不能多于两个的儿子。

二叉树遍历,先遍历,左子树,根节点、右子树。成为中序遍历。

先左子树,后右子树、再根节点,称为后序列遍历。

先根节点,后右子树,再左子树 ,称为先序遍历。

使二叉树成为二叉查找树的性质是:
对于树中的每个节点x、它的左子树中所有项的值小于x ,它的右子树中的值都大于X。

二叉查找树要求所有的项都能够排序。
/**
*
*
* 二叉查找树
*
* 二叉树,是一颗树,其中每个节点都不能多于两个的儿子。

二叉树遍历,先遍历,左子树,根节点、右子树。成为中序遍历。

先左子树,后右子树、再根节点,称为后序列遍历。

先根节点,后右子树,再左子树 ,称为先序遍历。

使二叉树成为二叉查找树的性质是:
对于树中的每个节点x、它的左子树中所有项的值小于x ,它的右子树中的值都大于X。

二叉查找树要求所有的项都能够排序。
*
*
* @author kuwo
*
*/
public class BinarySearchTree {

// 根节点
private BinaryNode root;

public BinarySearchTree() {
root = null;
}

public void makeEmpty() {
root = null;
}

public boolean isEmpty() {
return root == null;
}

public boolean contains(Integer x) {
return contains(x, root);
}

private BinaryNode findmBinaryNode() {
if (isEmpty()) {
return null;
}
return findMin(root);
}

private BinaryNode findMax(BinaryNode t) {
if (t != null) {
while (t.right != null) {
t = t.right;
}
}
return t;
}

/**
*
* @param t  开始打印的节点
*
*/
private void printTree(BinaryNode t){
if(t != null ){
printTree(t.left);
System.out.println(t.element);
printTree(t.right);
}
}

/**
*
* @param x
*            要删除的元素
* @param t
*            节点
* @return
*
*/
private BinaryNode remove(Integer x, BinaryNode t) {

if (t == null) {
return t;
}

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

if (compareResult < 0) {
t.left = remove(x, t.left);
} else if (compareResult > 0) {
t.right = remove(x, t.right);
} else if (t.left != null && t.right != null) {
t.element = findMin(t.right).element;
t.right = remove(t.element, t.right);
} else {
t = (t.left != null) ? t.left : t.right;
}
return t;
}

/**
*
* @param x
*            要插入的元素
* @param t
*            开始插入的节点
* @return
*/
private BinaryNode insert(Integer x, BinaryNode t) {

if (t == null) {
return 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);
}

return t;
}

/**
*
* @param t
*            根节点
* @return 找到的最小的节点
*/
private BinaryNode findMin(BinaryNode t) {
if (null == t) {
return null;
} else if (t.left == null) {
return t.left;
} else {
return findMin(t.left);
}
}

/**
* @param x
*            要查找的项
* @param t
*            二叉树的根节点
* @return 是否包含此项
*/
private boolean contains(Integer x, BinaryNode t) {

if (null == t) {
return false;
}

int compareResult = x.compareTo(x);
if (compareResult < 0) {
return contains(x, t.left);
} else if (compareResult > 0) {
return contains(x, t.right);
} else {
return true;
}
}

/**
*
* 二叉树的节点
*
* @author kuwo
*
*/
private static class BinaryNode {

Integer element;
BinaryNode left;
BinaryNode right;

public BinaryNode(int element) {
this(element, null, null);
}

public BinaryNode(int element, BinaryNode left, BinaryNode right) {
this.element = element;
this.left = left;
this.right = right;
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: