遍历二叉树的源代码如下:
package com.tree; import java.util.Scanner; public class TwoTree { int data; TwoTree left; TwoTree right; public TwoTree(int data){ this.data = data; left = null; right = null; } public void add(TwoTree root,int data){ if(data>root.data){ if(root.right==null){ root.right = new TwoTree(data); }else{ this.add(root.right, data); } }else{ if(root.left==null){ root.left = new TwoTree(data); }else{ this.add(root.left, data); } } } public static void fristleft(TwoTree root){ //先序遍历 if(root!=null){ System.out.print(root.data+" "); fristleft(root.left); fristleft(root.right); } } public static void fristroot(TwoTree root){ //中序遍历 if(root!=null){ fristroot(root.left); System.out.print(root.data+" "); fristroot(root.right); } } public static void fristright(TwoTree root){ //后序遍历 if(root!=null){ fristright(root.left); fristright(root.right); System.out.print(root.data+" "); } } public static int NodeNumber(TwoTree root){//叶子节点的个数 if(root==null){ return 0; } if(root.left==null&&root.right==null){ return 1; } return NodeNumber(root.left)+NodeNumber(root.right); } public static void main(String[] args) { // TODO 自动生成的方法存根 Scanner input = new Scanner(System.in); System.out.println("请输入总的节点的个数:"); int len = input.nextInt(); System.out.println("请输入节点数据"); TwoTree root = new TwoTree(input.nextInt()); //创建二叉树 for(int i=1;i<len;i++){ root.add(root, input.nextInt()); //向二叉树中插入数据 } System.out.println("先序遍历:"); fristleft(root); System.out.println("\n中序遍历:"); fristroot(root); System.out.println("\n后序遍历:"); fristright(root); System.out.println("\n叶子节点的个数: "+ NodeNumber(root)+"个"); System.exit(1); } }
运行的结果图为: