您的位置:首页 > 编程语言 > Java开发

java学习之二叉树的实现

2016-01-23 22:49 281 查看
二叉树是一种数据结构,每个节点都有两个子节点。

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

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

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

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

java实现:

package com.gh.Binary;

/**
* 二叉树的实现
*
* @author ganhang
*
*/
public class BinaryTreeDemo {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.add(8);
bt.add(3);
bt.add(10);
bt.add(1);
bt.add(6);
bt.add(14);
bt.add(4);
bt.add(7);
bt.add(13);
bt.print();//中序遍历可以从小到大排序
}
}


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();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: