二叉树 链表实现
public class BinaryTree<Key extends Comparable<Key>,Value>{
//所有的方法在此下面写
public void put (Key key ,Value value){
root = put(root,key,value);
}
public Node put(Node x, Key key, Value value){
//空树
if(x == null){
N++;
return new Node(key,value,null,null);
}
int c = key.compareTo(x.key);
if(c>0){
//右
x.right = put(x.right,key,value);
}else if(c<0){
//左
x.left= put(x.left,key,value);
}else{
//同KEY
x.value = vlaue;
}
return x;
}
public Value get(Key key){
return get(root,key);
}
public Value get(Node x,Key key){
if(x==null){
return null;
}
int c = key.compareTo(x.key);
if(c>0){
//右
return get(x.right,key);
}else if(c<0){
//左
return put(x.left,key);
}else{
//同KEY
return x.vlaue;
}
}
public void delete(Key key){
//删除时,替换的值为 右子树的左结点(右子树的上的最小值)
delete(root , key);
}
public Node delete(Node x,Key key){
if(x == null){
return null;
}
int c = key.compareTo(x.key);
if(c>0){
//右
x.right = delete(x.right ,key);
}else if(c<0){
//左
x.left = delete(x.left ,key);
}else{
//同KEY
N--;
if(x.right == null){
return x.left;
}
if(x.left == null){
return x.right;
}
Node minnode = x.right;
while(minnode.left ! = null){
minnode = minnode.left;
}
//删除右子树最小结点
Node n= x.right;
while(n.left!=null){
if(n.left.left == null){
n.left =null;
}else{
n=n.left;
}
}
minnode.left =x.left;
minnode .right= x.right;
x=minnode;
}
}
reutn x;
}
public Key min(){
return min(root).key;
}
public Node min(Node x){
if(x.left!=null){
return min(x.left);
}else{
return x;
}
}
- 前序遍历
public Queue<Key> preErgodic(){
Queue<Key> keys = new Queue<>();
preErgodic(root,keys);
return keys;
}
private void preErgodic(Node x,Queue<Key> keys){
if (x==null){
return;}
keys.enqueue(x.key)
if(x.left!=null){
preErgodic(x.left,keys)
}
if(x.right!=null){
preErgodic(x.right,keys)
}
}
- 中序遍历
//原理同上
- 后序遍历
//原理同上
- 层序遍历
public Queue<Key> layerErgodic(){
//
Queue<Key> keys =new Queue<>();
Queue<Node> nodes=new Queue<>();
nodes.enqueue(root);
while(!nodes.isEmpty()){
Node n = nodes.dequeue();
keys.enqueue(n.key);
if(n.left!=null){
nodes.enqueue(n.left);
}
if(n.right!=null){
nodes.enqueue(n.right);
}
}
return keys ;
}
- 最大深度
public int maxDepth(){
return maxDepth(root);
}
public int maxDepth(Node x){
//递归的思想
if(x == null){
return 0;
}
int max = 0;
int maxl = 0;
int maxr = 0;
if(x.left!=null){
maxl = maxDepth(x.left);
}
if(x.right!=null){
maxr = maxDepth(x.right);
}
max = maxl>maxr?maxl+1:maxr+1;
return max;
}
- 折纸思想
左子节点为下折痕
右子节点为上折痕
产生这样的树,层序产生
接着中序遍历这样的树
public static Node<string> createTree(int N){
Node<String> root =null;
fot(int i =0 ;i<N;i++){
if (i==0){
root =new Node("down",null,null);
continue;
}
Queue<Node> queue =new queue<>();
queue.enqueue(root);
while(!queue.isEmpty()){
Node<string> t = queue.dequeue();
if(t.left!=null){
queue.enqueue(t.left);
}
if(t.right!=null){
queue.enqueue(t.right);
}
if(t.left == null && t.right == null){
t.left=new Node<String>("down",null,null);
t.right=new Node<String>("right",null,null);
}
}
}
return root;
}
public static void printTree(Node<String> root{
//中序遍历
}