java 构建二叉排序树并先序遍历
//构建二叉排序树并先序遍历
public class BinaryTree{
static NodeTree root;
public void insert(int data) {
NodeTree newRoot=new NodeTree(data);
if(root==null) {
root=newRoot;
}else {
NodeTree cur=root;
NodeTree parent;
while(true) {
parent=cur;
if(data<cur.data) {
if(cur.left==null) {
parent.left=newRoot;
return;
}else {
cur=cur.left;
}
}else {
if(cur.right==null) {
parent.right=newRoot;
return;
}else {
cur=cur.right;
}
}
}
}
}
public void builderTree(int[] a) {
for(int i=0;i<a.length;i++) {
insert(a[i]);
}
}
public void inOrder(NodeTree root) {
if(root!=null) {
System.out.print(root.data);
inOrder(root.left);
inOrder(root.right);
}
}
public void inOrder() {
this.inOrder(this.root);
}
}
class NodeTree{
int data;
NodeTree left;
NodeTree right;
public NodeTree(int data) {
this.data=data;
}
}