结点类
package tree;
public class TreeNode<T> {
public T data; //数据域
public TreeNode<T> left,right;
public TreeNode(T data, TreeNode<T> left,TreeNode<T> right){
this.data = data;
this.left = left;
this.right = right;
}
public TreeNode(T data){
this(data,null, null);
}
public String toString(){
return this.data.toString();
}
//判断是否为页子结点
public boolean isLeaf(){
return this.left == null&& this.right == null;
}
}
二叉树
package tree;
public class Demo1Tree<T> {
public TreeNode<T> root;
public Demo1Tree(){
this.root = null;
}
public boolean isEmpty(){
return this.root == null;
}
//插入x作为根结点
public TreeNode<T> insert(T x){
return this.root = new TreeNode<T>(x,this.root,null);
}
//插入x作为parent结点的左右子结点,leftChild == true ,取值为左,反之为右
public TreeNode<T> insert(TreeNode<T> parent, T x,boolean leftChild){
if(x == null){
return null;
}
if(leftChild)
//作为左孩子
return parent.left = new TreeNode<T>(x,null,parent.right);
//作为右孩子
return parent.right = new TreeNode<T>(x,null,parent.right);
}
//删除parent结点的左右子树
public void remove(TreeNode<T> parent, boolean leftChild){
if(leftChild)
parent.left = null;
else
parent.right = null;
}
//全部删除
public void clear(){
this.root = null;
}
//根次序遍历序列
public void preorder(){
preorder(this.root);
System.out.println();
}
public void preorder(TreeNode<T> p){
if(p != null){
System.out.print(p.data.toString()+ " ");
preorder(p.left);
preorder(p.right);
}
}
//获取结点个数
public int size(){
return size(root);
}
public int size(TreeNode<T> p){
if(p == null) return 0;
return 1+size(p.left)+size(p.right);
}
//获取高度
public int height(){
return height(root);
}
public int height(TreeNode<T> p){
if(p == null)
return 0;
int lh = height(p.left); //返回左子树的高度
int rh = height(p.right); //返回右子树的高度
return (lh>rh)?lh+1:rh+1;
}
//查找并返回首次出现的关键字为key的元素
public T search(T key){
return searchNode(root,key).data;
}
// public TreeNode<T> searchNode(T key){
// return searchNode(root,key);
// }
public TreeNode<T> searchNode(TreeNode<T> p, T key){
if(p == null || key == null) return null;
if(p.data.equals(key)) return p;
//递归在左子树中找
TreeNode<T> find = searchNode(p.left,key);
//找不到换右子树
if(find == null) find = searchNode(p.right,key);
return find;
}
//返回node结点的父母结点,若空树、未找到或node为根结点,则返回null
public TreeNode<T> getParent(TreeNode<T> node){
if(root == null || node == null || node ==root)
return null;
return getParent(root,node);
}
public TreeNode<T> getParent(TreeNode<T> p , TreeNode<T> node){
//空树
if(p == null)
return null;
if(p.left == node || p.right == node)
return p;
//从左子树找
TreeNode<T> find = getParent(p.left,node);
//左边没有换右边找
if(find == null)
find = getParent(p.right,node);
return find;
}
}