创建二叉树类
public class tree { int data; tree left; tree right; public tree(int data, tree left, tree right) { super(); this.data = data; this.left = left; this.right = right; } public tree(int data) { this.data=data; this.left=null; this.right=null; } public void insert(tree t,int data){ if(data>this.data){ if(t.right==null){ t.right=new tree(data); }else{ t.insert(right,data); } }else if(data<=this.data){ if(t.left==null){ t.left=new tree(data); }else{ t.insert(left,data); } } } }
遍历二叉树
public class BinaryTree { ; public static void main(String[] args) { int [] arr ={21,33,44,23,56,79,456,32,98,7,5}; tree root = new tree(arr[0]); for (int i = 1; i < arr.length; i++) { root.insert(root,arr[i]); } preOrder(root); } public static void preOrder(tree root){ if(root!=null){ System.out.print(root.data+"-"); preOrder(root.left); preOrder(root.right); } //System.out.println("先根遍历"); } }