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();
            }
        }
    }
}

 

posted @ 2016-01-23 22:49  CodeNoob  阅读(283)  评论(0编辑  收藏  举报