給你一個排序二叉樹和一個n值,把二叉樹分成兩半,一半是<n,另一半>n
package 二叉樹分割;
class Node{
int num;
Node lnode,rnode;
public Node(int num) {
super();
this.num = num;
}
}
public class Main {
static Node min,max;
public static void fen(Node root,int num){
if(root==null) return;
if(root.num==num){
addNode1(min, root.lnode);
addNode1(max,root.rnode);
}else{
if(root.num>num){
Node left=root.lnode;
root.lnode=null;
addNode1(max, root);
fen(left, num);
}else{
Node right=root.rnode;
root.rnode=null;
addNode1(min, root);
fen(right,num);
}
}
}
public static Node addNode(Node root,int num){
if(root==null)
return new Node(num);
else{
if(root.num==num) return root;
if(root.num>num){
root.lnode=addNode(root.lnode, num);
}else{
root.rnode=addNode(root.rnode, num);
}
return root;
}
}
public static Node addNode1(Node root,Node newRoot){
if(newRoot==null)
return root;
if(root==null)
return newRoot;
else{
if(root.num>newRoot.num){
root.lnode=addNode1(root.lnode, newRoot);
}else{
root.rnode=addNode1(root.rnode, newRoot);
}
return root;
}
}
public static void out(Node root){
if(root==null) return;
out(root.lnode);
System.out.print(root.num+" ");
out(root.rnode);
}
public static void main(String[] args) {
int[] a={3,1,0,2,4,5,7,21,9};
Node root=null;
for(int i=0;i<a.length;++i)
root=addNode(root, a[i]);
out(root);
System.out.println();
min=new Node(9999);max=new Node(9999);
int find=8;
addNode(root,find);
fen(root, find);
out(min.lnode);
System.out.println();
out(max.lnode);
}
}