java实现树的遍历

package tree;
import java.util.*;
public class BinaryTree {
	public TreeNode root;
	public void insert(int date)
	{
		TreeNode newNode=new TreeNode(date);
		if(root==null)
		{
			root=newNode;
			return;
		}
		TreeNode currentNode=root;
		while(true)
		{
			if(newNode.date<currentNode.date)
			{
				if(currentNode.left!=null)
				{
					currentNode=currentNode.left;
				}
				else {
						currentNode.left=newNode;
						return;
					 }
			}
			else {
				if(currentNode.right!=null)
				{
					currentNode=currentNode.right;
				}
				else {
						currentNode.right=newNode;
						return;
					 }
			}
		}
	}

//遍历:遍历的方式------------>深度优先遍历,广度优先遍历 递归方法
//深度优先遍历
//先序遍历
public void beforeOrder(TreeNode root)
{
	if(root==null)
	{
		return;
	}
	System.out.println(""+root.date);
	beforeOrder(root.left);
	beforeOrder(root.right);
}
//中序遍历
public void inOrder(TreeNode root)
{
	if(root==null)
	{
		return;
	}
	inOrder(root.left);
	System.out.println(""+root.date);
	inOrder(root.right);
}
//后序遍历
public void afterOrder(TreeNode root)
{
	if(root==null)
	{
		return;
	}
	afterOrder(root.left);
	afterOrder(root.right);
	System.out.println(""+root.date);
}
//广度优先遍历
public void levelOrder()
{
	LinkedList<TreeNode> queue=new LinkedList<>();
	queue.add(root);
	while(!queue.isEmpty())
	{
		root=queue.pop();
		System.out.print(root.date+" ");
		if(root.left!=null)
		{
			queue.add(root.left);
		}
		if(root.right!=null)
		{
			queue.add(root.right);
		}
	}
}
//查询------>如果树中有这个值,那么返回true,否则返回false
public boolean searchVal(int val)
{
	TreeNode newnode=root;
	while(newnode!=null)
	{
		if(val<newnode.date)
		{
			newnode=newnode.left;
		}
		if(val==newnode.date)
		{
			return true;
		}
		if(val>newnode.date)
		{
			newnode=newnode.right;
		}
	}
	return false;
	
}
}
package tree;

public class TreeNode {
	public int date;
	public TreeNode left;
	public TreeNode right;
	
	public TreeNode(int date)
	{
		this.date=date;
	}
	
	public String toString()
	{
		return "TreeNode{"+"date="+date+",left="+left+",right="+right+'}';
	}
}

深度优先遍历

 

先序遍历:根 左 右

ABEKLFDHMJ

中序遍历:左 根 右

后序遍历:左 右 根

广度优先遍历:

ABDEFHJKLM

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值