【Java】利用数组建立二叉树 & 建立二叉搜索树 & 层序遍历 的简单实现

import java.util.LinkedList;
import java.util.Queue;

public class Tree {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
        TreeNode() { }
    }

    // 用数组建立二叉排序树
    public static TreeNode bulidBST(int[] A) {
        TreeNode root = new TreeNode(A[0]);
        for (int i=1; i<A.length; i++) {
            createBST(root, A[i]);
        }
        return root;
    }

    private static void createBST(TreeNode node, int val) {
        if (val<node.val) {
            if (node.left == null) {
                node.left = new TreeNode(val);
            } else
                createBST(node.left, val);
        } else {
            if (node.right == null) {
                node.right = new TreeNode(val);
            } else
                createBST(node.right, val);
        }
    }

    // 用数组建立普通二叉树
    public static TreeNode buildBinaryTree(TreeNode root, int[] A, int index) {
        if (index>A.length/2)
            return root;
        if (index==1)
            root.val = A[0];
        root.left = new TreeNode(A[index*2-1]);
        root.right = new TreeNode(A[index*2]);
        buildBinaryTree(root.left, A,index+1);
        buildBinaryTree(root.right, A,index+2);
        return root;
    }

    // 层序遍历打印二叉树
    public static void levelOrderPrintBST(TreeNode root) {
        Queue<TreeNode> queue = new LinkedList<>();
        if (root==null)
            return;
        queue.offer(root);

        while(!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node==null)
                continue;
            else
                System.out.println(node.val);
            queue.offer(node.left);
            queue.offer(node.right);
        }
    }

    public static void main(String[] args) {
        levelOrderPrintBST(bulidBST(new int[]{2,1,3,5,7}));
        levelOrderPrintBST(buildBinaryTree(new TreeNode(), new int[]{2,1,3,5,7}, 1));
    }
}

猜你喜欢

转载自blog.csdn.net/Art1st_D/article/details/89462779