Java_二叉树用途

赫夫曼树

  • 赫夫曼树的构造

  • 赫夫曼树构造过程

赫夫曼编码
Paste_Image.png

查找二叉树


/**
 * 查找二叉树
 * @author Administrator
 *
 */
public class SearchBinaryTree {
    //根结点
    public TreeNode root;

    public class TreeNode {
        public int index;
        public int data;
        public TreeNode leftChild;
        public TreeNode rightChild;
        public TreeNode parent;// 父节点

        public TreeNode(int index, int data) {
            this.data = data;
        }
    }

    /**
     * 二叉树左边孩子都比根结点小,右边孩子都比根结点大
     * 
     * @param dataList
     */
    public TreeNode buildSearchTree(int index, int data) {
        TreeNode node = null;
        TreeNode parentNode = null;
        if (root == null) {
            node = new TreeNode(index, data);
            root = node;
        }

        node = root;
        // 查找合适的位置
        while (node != null) {
            parentNode = node;
            if (node.data > data) {
                node = node.leftChild;
            } else if (node.data < data) {
                node = node.rightChild;
            } else {
                return node;
            }
        }
        //退出while循环时,node为null需要创建
        node = new TreeNode(index, data);
        if (parentNode.data > data) {
            parentNode.leftChild = node;
        } else if (parentNode.data < data) {
            parentNode.rightChild = node;
        }
        node.parent = parentNode;
        return node;
    }

    /**
     * 中序遍历二叉树
     * @param node
     */
    public void print(TreeNode node) {
        if (node == null) {
            return;
        }
        print(node.leftChild);
        System.out.print(" "+node.data);
        print(node.rightChild);
        
    }

    public static void main(String[] args) {
        SearchBinaryTree binaryTree = new SearchBinaryTree();
        int[] array = { 3, 2, 6, 12, 5, 1, 28, 20, 30, 15 };
        for (int i = 0; i < array.length; i++) {
            binaryTree.buildSearchTree(i, array[i]);
        }
        
        binaryTree.print(binaryTree.root);
    }

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 树的概述 树是一种非常常用的数据结构,树与前面介绍的线性表,栈,队列等线性结构不同,树是一种非线性结构 1.树的定...
    Jack921阅读 9,935评论 1 31
  • 四、树与二叉树 1. 二叉树的顺序存储结构 二叉树的顺序存储就是用数组存储二叉树。二叉树的每个结点在顺序存储中都有...
    MinoyJet阅读 5,513评论 0 7
  • 第一章 绪论 什么是数据结构? 数据结构的定义:数据结构是相互之间存在一种或多种特定关系的数据元素的集合。 第二章...
    SeanCheney阅读 11,089评论 0 19
  • 概念 树是什么 树(Tree)是n(n>=0)个结点的有限集。 n = 0的树是空树。 在任意一棵非空树中: 有且...
    刚刚悟道阅读 10,535评论 1 16
  • 盈盈掌上燕 只影舞秋风 痴情换薄情 皓齿珠黄 亏却多少青青 当年鸳鸯金勾栏 剩苍苍发垂 幸得寒心不惧冰 今宵红袖火...
    夹馅锅锅阅读 812评论 0 0