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);
	}
发布了34 篇原创文章 · 获赞 80 · 访问量 2027

猜你喜欢

转载自blog.csdn.net/jackzhang11/article/details/102624956
今日推荐