zoukankan      html  css  js  c++  java
  • java学习之二叉树的实现

    二叉树是一种数据结构,每个节点都有两个子节点。

    二叉树的遍历有三种方式,

    先序遍历是 根节点,左子树,右子树;

    中序遍历是 左子树,根节点,右子树;

    后序遍历是 左子树,右子树,根节点;

    java实现:

     1 package com.gh.Binary;
     2 
     3 /**
     4  * 二叉树的实现
     5  * 
     6  * @author ganhang
     7  * 
     8  */
     9 public class BinaryTreeDemo {
    10     public static void main(String[] args) {
    11         BinaryTree bt = new BinaryTree();
    12         bt.add(8);
    13         bt.add(3);
    14         bt.add(10);
    15         bt.add(1);
    16         bt.add(6);
    17         bt.add(14);
    18         bt.add(4);
    19         bt.add(7);
    20         bt.add(13);
    21         bt.print();//中序遍历可以从小到大排序
    22     }
    23 }
    package com.gh.Binary;
    /**
     * 二叉树的管理类
     * @author ganhang
     *
     */
    public class BinaryTree {
        private Node root;
        public void add(int data) {
            if (root == null) {
                root = new Node(data);
            } else {
                root.addNode(data);
            }
        }
        public void print() {
            if (root != null) {
                root.printNode();
            }
        }
    
        class Node {
            private int data;
            private Node left;
            private Node right;
            public Node(int data) {
                this.data = data;
            }
            public void addNode(int data) {
                if (data < this.data) {
                    if (this.left == null) {
                        this.left=new Node(data);
                    } else {
                        this.left.addNode(data);
                    }
                } else if (data >= this.data) {
                    if (this.right == null) {
                        this.right=new Node(data);
                    } else {
                        this.right.addNode(data);
                    }
                }
            }
            //二叉树的中序遍历
            public void printNode() {
                if (this.left != null) {
                    this.left.printNode();
                }
                System.out.println(this.data + " ");
                if (this.right != null) {
                    this.right.printNode();
                }
            }
        }
    }
  • 相关阅读:
    [转]天龙八部的BillingServer
    [转]天龙八部服务器端Lua脚本系统
    [转]天龙八部服务器端-共享内存的设计
    TCPSocket v1.0 for cocos2d-x下载
    httpclient模拟浏览器getpost
    常用的32中算法
    我在城市快节奏中的慢生活
    分段与分页机制小结
    lua中dofile、loadfile、require区别
    两个链表相交以及第一个公共节点的问题
  • 原文地址:https://www.cnblogs.com/ganhang-acm/p/5154287.html
Copyright © 2011-2022 走看看