简单写了一个二叉树的实现-递归
二叉树的节点设计及其接口:
public class TreeNode {
//键值对
private int key,value;
//树的深度
private int N;
//左右节点
private TreeNode left,right;
public TreeNode(int key,int value,int N){
this.key = key;
this.value = value;
this.N = N;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public int getN() {
return N;
}
public void setN(int n) {
N = n;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
二叉树的生成及其遍历
public class BST {
static int Key = 0;
//初始化根节点
static TreeNode treeNode = new TreeNode(0,5,0);
//普通二叉树插入(这里使用int类型)
public static void add(int value,TreeNode treeNode,int Key,int N){
//深度在原节点深度上+1
N = treeNode.getN()+1;
Key = treeNode.getKey()+1;
//左右子树判定
if (treeNode.getValue() > value ){
if (treeNode.getLeft() == null){
//左子树未生成节点
//新建节点
treeNode.setLeft(new TreeNode(++Key,value,N));
}else {
//左子树已经生成节点
add(value,treeNode.getLeft(),Key,N);
}
}else {
if (treeNode.getRight() == null){
//右子树未生成节点
//新建节点
treeNode.setRight(new TreeNode(++Key,value,N));
}else {
//右子树已经生成节点
add(value,treeNode.getRight(),Key,N);
}
}
}
//前序遍历 - 递归
public static void DLR(TreeNode treeNode){
//DLR:根->左子树->右子数
System.out.print(treeNode.getValue()+" ");
if (treeNode.getLeft() == null && treeNode.getRight() == null)return;
if (treeNode.getLeft() != null) DLR(treeNode.getLeft());
if (treeNode.getRight() != null) DLR(treeNode.getRight());
}
//中序遍历 - 递归
public static void LDR(TreeNode treeNode){
//LDR: 左 -> 根 -> 右
if (treeNode.getLeft() != null) {
LDR(treeNode.getLeft());
}
System.out.print(treeNode.getValue()+" ");
if (treeNode.getRight() != null)
LDR(treeNode.getRight());
}
//后序遍历 - 递归
public static void LRD(TreeNode treeNode){
//LDR: 左 -> 右 -> 根
if (treeNode.getLeft() != null) {
LRD(treeNode.getLeft());
}
if (treeNode.getRight() != null){
LRD(treeNode.getRight());
}
System.out.print(treeNode.getValue()+" ");
}
public static void add(int value){
add(value,treeNode,Key,0);
}
public static void main(String[] args) {
//初始的根节点为5
BST.add(7);
BST.add(8);
BST.add(6);
BST.add(3);
BST.add(1);
BST.add(9);
//前序遍历结果
System.out.print("递归-前序遍历:");
BST.DLR(treeNode);
System.out.println();
//中序遍历结果
System.out.print("递归-中序遍历:");
BST.LDR(treeNode);
System.out.println();
//后序遍历结果
System.out.print("递归-后序遍历:");
BST.LRD(treeNode);
System.out.println();
}
}