• 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();
                }
            }
        }
    }
  • 相关阅读:
    各个数字类型取值范围以及推理
    进制转换原理
    位运算操作符_
    读取文件内容
    java中thread的start()和run()的区别
    二进制的负数转换
    位运算符号
    Hadoop的辉煌还能延续多久?
    Hadoop 新 MapReduce 框架 Yarn 详解
    MapReduce工作原理讲解
  • 原文地址:https://www.cnblogs.com/ganhang-acm/p/5154287.html
Copyright © 2020-2023  润新知