二叉树的创建、插入、遍历
二叉树:左子树的值小于根节点的值,右子树的值大于根节点的值。
此代码描述了二叉树的创建,插入,先序遍历,中序遍历,后序遍历。
package ss; import java.io.BufferedReader; import java.io.InputStreamReader; public class BinaryTree{ private int data; BinaryTree left; BinaryTree right; public BinaryTree(int data){ this.data=data; left=null; right=null; } public void insert(BinaryTree root,int data){ if(data>root.data){ if(root.right==null){ root.right=new BinaryTree(data); }else{ this.insert(root.right, data); } }else{ if(root.left==null){ root.left=new BinaryTree(data); }else{ this.insert(root.left, data); } } } public static void Preorder(BinaryTree root){//先序遍历 if(root!=null){ System.out.print(root.data+" "); Preorder(root.left); Preorder(root.right); } } public static void InOrder(BinaryTree root){//中序遍历 if(root!=null){ InOrder(root.left); System.out.print(root.data+" "); InOrder(root.right); } } public static void PostOrder(BinaryTree root){ if(root!=null){ PostOrder(root.left); PostOrder(root.right); System.out.print(root.data+" "); } } public static void main(String[] args){ int[] array={12,76,35,22,16,48,90,46,9,40}; BinaryTree bt=new BinaryTree(array[0]); for(int i=1;i<array.length;i++){ bt.insert(bt, array[i]); } Preorder(bt); System.out.println(""); InOrder(bt); System.out.println(""); PostOrder(bt); System.out.println(""); } }
打印结果:
12 9 76 35 22 16 48 46 40 90 //先序
9 12 16 22 35 40 46 48 76 90 //中序
9 16 22 40 46 48 35 90 76 12//后序