public class BinaryTree {
public static void main(String[] args)
{
int[] arr = {2,4,6,8,22,34,77,44};
BinaryTree bt = new BinaryTree();
for(int i=0;i<arr.length;i++)
{
bt.buildTree(bt.root, arr[i]);
}
bt.preOrder(bt.root);
bt.inOrder(bt.root);
bt.postOrder(bt.root);
}
private static Node root;
private class Node{
private Node left;
private Node right;
private int data;
public Node(int data)
{
this.data = data;
}
}
public BinaryTree()
{
this.root = null;
}
public static void buildTree(Node node,int data)
{
if(root==null)
{
root = new Node(data);
}
else
{
if(data<node.data)
{
if(node.left==null)
node.left = new Node(data);
else
buildTree(node.left,data);
}
else if(data>node.data)
{
if(node.right==null)
node.right = new Node(data);
else
buildTree(node.right,data);
}
}
}
public static void preOrder(Node node)//前序遍历
{
if(node!=null)
{
System.out.println(node.data);
preOrder(node.left);
preOrder(node.right);
}
}
public static void inOrder(Node node)//中序遍历
{
if(node!=null)
{
inOrder(node.left);
System.out.println(node.data);
inOrder(node.right);
}
}
public static void postOrder(Node node)//后序遍历
{
if(node!=null)
{
postOrder(node.left);
postOrder(node.right);
System.out.println(node.data);
}
}
}
二叉树的创建和三种遍历方式
最新推荐文章于 2022-05-24 19:59:56 发布