Java二叉树的创建及遍历

	//定义二叉树节点
	public static class Node {
		Node left;	//左节点
		Node right;		//右节点
		Integer value;	//节点值
		
		public void add(Integer v)	//插入节点
		{
			if(value == null)
				value = v;
			else
			{
				if(v-this.value<=0)
				{
					if(this.left==null)
						this.left = new Node();
					left.add(v);
				}
				else
				{
					if(this.right==null)
						this.right = new Node();
					right.add(v);
				}
			}
		}
	}
	
	//二叉树先序遍历
	public static void preOrderTraverse(Node root)
	{
		if(root == null) return;
		else
		{
			System.out.print(root.value + " ");
			preOrderTraverse(root.left);
			preOrderTraverse(root.right);
		}
	}
	
	//二叉树中序遍历
	public static void inOrderTraverse(Node root)
	{
		if(root == null) return;
		else
		{
			inOrderTraverse(root.left);
			System.out.print(root.value + " ");
			inOrderTraverse(root.right);
		}
	}
	
	//二叉树后序遍历
	public static void postOrderTraverse(Node root)
	{
		if(root == null) return;
		else
		{
			postOrderTraverse(root.left);
			postOrderTraverse(root.right);
			System.out.print(root.value + " ");
		}
	}
	
	//二叉树层序遍历
	public static void levelOrderTraverse(Node root)
	{
		LinkedList<Node> arr = new LinkedList<>();
		arr.offer(root);
		while(!arr.isEmpty())
		{
			int size = arr.size();
			for(int i = 0; i < size; i++)
			{
				Node tmp = arr.poll();
				System.out.print(tmp.value + " ");
				if(tmp.left!=null) arr.offer(tmp.left);
				if(tmp.right!=null) arr.offer(tmp.right);
			}
		}
	}

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int arr[] = new int[] { 67, 7, 30, 73, 10, 8, 78, 81, 11, 74 };
		Node root = new Node();
		//创建二叉树
		for(int x: arr)
		{
			root.add(x);
		}
		preOrderTraverse(root);
		System.out.println();
		inOrderTraverse(root);
		System.out.println();
		postOrderTraverse(root);
		System.out.println();
		levelOrderTraverse(root);
	}
  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值