IdeaGrace博客» Blog Archive » 二叉树的创建、前序遍历、中序遍历、后 ...
May 22, 2010 – 10:08 am

经常考的数据结构题目。

package tree;

public class Tree {

    private int data;// 数据节点
    private Tree left;// 左子树
    private Tree right;// 右子树

    public Tree(int data) {
        this.data = data;
        this.left = null;
        this.right = null;
    }

    /**
     * 创建二叉树,返回根结点
     *
     * @param input
     * @return
     */
    public static Tree createTree(int[] input) {
        Tree root = null;
        Tree temp = null;
        for (int i = 0; i < input.length; i++) {
            // 创建根节点
            if (root == null) {
                root = temp = new Tree(input[i]);
            } else {
                // 回到根结点
                temp = root;
                // 添加节点
                while (temp.data != input[i]) {
                    if (input[i] <= temp.data) {
                        if (temp.left != null) {
                            temp = temp.left;
                        } else {
                            temp.left = new Tree(input[i]);
                        }
                    } else {
                        if (temp.right != null) {
                            temp = temp.right;
                        } else {
                            temp.right = new Tree(input[i]);
                        }
                    }
                }
            }
        }
        return root;
    }

    /**
     * 前序遍历
     *
     * @param tree
     */
    public static void preOrder(Tree tree) {
        if (tree != null) {
            System.out.print(tree.data + " ");
            preOrder(tree.left);
            preOrder(tree.right);
        }
    }

    /**
     * 中序遍历
     *
     * @param tree
     */
    public static void midOrder(Tree tree) {
        if (tree != null) {
            midOrder(tree.left);
            System.out.print(tree.data + " ");
            midOrder(tree.right);
        }
    }

    /**
     * 后序遍历
     *
     * @param tree
     */
    public static void posOrder(Tree tree) {
        if (tree != null) {
            posOrder(tree.left);
            posOrder(tree.right);
            System.out.print(tree.data + " ");
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] input = { 4, 2, 6, 1, 3, 5, 7 };
        Tree tree = createTree(input);
        System.out.print("前序遍历:");
        preOrder(tree);
        System.out.print("\n 中序遍历:");
        midOrder(tree);
        System.out.print("\n 后序遍历:");
        posOrder(tree);
    }
}
 


1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)



相关日志:





郑重声明:资讯 【IdeaGrace博客» Blog Archive » 二叉树的创建、前序遍历、中序遍历、后 ...】由 发布,版权归原作者及其所在单位,其原创性以及文中陈述文字和内容未经(企业库qiyeku.com)证实,请读者仅作参考,并请自行核实相关内容。若本文有侵犯到您的版权, 请你提供相关证明及申请并与我们联系(qiyeku # qq.com)或【在线投诉】,我们审核后将会尽快处理。
—— 相关资讯 ——