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