二叉树遍历算法

遍历二叉树的源代码如下:

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);
	}
}


运行的结果图为:




  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值