二叉排序树实现及各类遍历

来源:互联网 发布:上海达内java教育地址 编辑:程序博客网 时间:2024/04/30 15:18

二叉排序树具有性质:

① 如果左子树不为空,则左子树上的所有节点的值均小于根节点的值;②如果右子树不为空,则右子树上所有节点的值均大于根节点的值;③左右子树均为二叉排序树。


//树节点类class Node{public int data;//节点的数值public Node left;//左子节点public Node right;//右子节点//构造函数public Node(){}public Node(int data){this.data=data;this.left=null;this.right=null;}}
//二叉树遍历类class OrderBinTree{/* * 先序遍历-->根节点,左子树,右子树(递归实现) */public static void preOrder(Node root){if(root!=null){System.out.print(root.data+" ");//输出根节点数值preOrder(root.left);//左子树preOrder(root.right);//右子树}}/* * 中序遍历-->左子树,根节点,右子树(递归实现) */public static void inOrder(Node root){if(root!=null){inOrder(root.left);//左子树System.out.print(root.data+" ");//输出根节点数值inOrder(root.right);//右子树}}/* * 后序遍历-->左子树,右子树,根节点(递归实现) */public static void postOrder(Node root){if(root!=null){postOrder(root.left);//左子树postOrder(root.right);//右子树System.out.print(root.data+" ");//输出根节点数值}}/* * 层次遍历(采用队列实现) */public static void layerOrder(Node root){if(root!=null){Queue<Node> q=new LinkedList<Node>();q.add(root);while(!q.isEmpty()){ //当前队列不为空Node n=q.poll();System.out.print(n.data+" ");if(n.left!=null){q.add(n.left);//左子树节点加入队列}if(n.right!=null){q.add(n.right);//右子树节点加入队列}}}}}
public class BinSortTree {private Node root;//根节点//构造函数public BinSortTree(){root=null;}/* * 将数据插入到排序二叉树中—-->左子树数值小于根节点数值,右子树数值大于根节点数值 */public void insertData(int data){Node newNode=new Node(data);if(root==null)root=newNode;else{Node current=root;Node parent;while(true){parent=current;//小于当前节点的值,应插入到左子树if(data<current.data){current=current.left;if(current==null){parent.left=newNode;//找到位置后,插入数据return;//跳出循环,结束函数}}//大于当前节点的值,应插入到右子树else{current=current.right;if(current==null){parent.right=newNode;return;}}}}}//创建二叉排序树public void buildTree(int[] data){for (int i = 0; i < data.length; i++) {insertData(data[i]);}}public static void main(String[] args) {BinSortTree tree=new BinSortTree();int[] data={2,8,7,4,9,3,1,6,7,5};tree.buildTree(data);//先序遍历System.out.print("先序遍历: ");OrderBinTree.preOrder(tree.root);System.out.println();//中序遍历System.out.print("中序遍历: ");OrderBinTree.inOrder(tree.root);System.out.println();//后序遍历System.out.print("后序遍历: ");OrderBinTree.postOrder(tree.root);System.out.println();//层次遍历System.out.print("层次遍历: ");OrderBinTree.layerOrder(tree.root);}}




0 0