//定义二叉树节点
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);
}
Java二叉树的创建及遍历
最新推荐文章于 2023-12-14 15:54:39 发布