二叉树的创建及输出
main方法
中序遍历是一个升序遍历
package com.google.staticinstance;
/**
* 二叉树
*/
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() {
root.printnode();
}
//内部类
private class Node{
private int data;
private Node leftnode;
private Node rightnode;
public Node(int data) {
this.data = data;
}
public void addnode(int data) {
if(data<this.data) {
if(this.leftnode==null) {
leftnode = new Node(data);
}else {
leftnode.addnode(data);
}
}else {
if(this.rightnode==null) {
rightnode = new Node(data);
}else{
rightnode.addnode(data);
}
}
}
//中序遍历(左->根->右)
public void printnode() {
if(this.leftnode!=null) {
this.leftnode.printnode();
}
System.out.print(this.data+" ");
if(this.rightnode!=null) {
this.rightnode.printnode();
}
}
}
}
main方法
package com.google.staticinstance;
public class TestBinaryTree {
public static void main(String[] args) {
BinaryTree bt = new BinaryTree();
bt.add(3);
bt.add(2);
bt.add(8);
bt.add(4);
bt.add(7);
bt.add(6);
bt.add(0);
bt.add(9);
bt.add(1);
bt.print();
}
}
![](https://i-blog.csdnimg.cn/blog_migrate/3d89022ae6e01b931c33b91e97ccad3b.png)
中序遍历是一个升序遍历