二叉树的存储及递归计算节点数目
二叉树的概念倒是挺好理解,主要问题在如何通过输入来存储二叉树(这里不是运用数据转换的方法),写的有些复杂,还请多多见谅
package binary_tree;
import java.util.Scanner;
public class Demotree {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入根节点的数据:");
Bitree tree = new Bitree(sc.next());
BiTNode tem = tree.root;
while (true) {
System.out.println("请输入位置 (节点位置 0为左,1为右)");
int pos = sc.nextInt();
System.out.println("请输入插入的数据");
String data = sc.next();
tem = tree.addNode(tem, data, pos);
System.out.println("是否还要添加或者返回根节点?(2为返回根节点,1为继续为下一节点添加,0位不再添加)");
int flag = sc.nextInt();
if (flag == 2) {
tem = tree.root;
}
if(flag == 1) {
continue;
}
if (flag == 0) {
break;
}
}
System.out.println("前序遍历为:");
tree.Traversal1(tree.root);
System.out.println();
System.out.println("节点的个数为:" + tree.nodeNUM);
}
}
class BiTNode {
String data;
BiTNode lchild;
BiTNode rchild;
public BiTNode() {
super();
}
public BiTNode(String data, BiTNode lchild, BiTNode rchild) {
super();
this.data = data;
this.lchild = lchild;
this.rchild = rchild;
}
}
class Bitree {
static int nodeNUM = 0;// 节点数
BiTNode root;// 根节点
public Bitree() {
super();
}
public Bitree(String data) {
this.root = new BiTNode(data, null, null);
}
/**
*
* parent指定节点 data 添加节点数据 pos 节点位置 0为左,1为右
*/
public BiTNode addNode(BiTNode parent, String data, int pos) {
if (parent == null) {
try {
throw new Exception("该节点为空,无法添加节点");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
if (pos == 0 && parent.lchild == null) {
// 添加左子树
parent.lchild = new BiTNode(data, null, null);
return parent.lchild;
} else if (pos == 1 && parent.rchild == null) {
// 添加右子树
parent.rchild = new BiTNode(data, null, null);
return parent.rchild;
} else if (pos == 0 && parent.lchild != null) {
System.out.println("该节点已满,返回该已满的节点继续添加");
return parent.lchild;
} else if (pos == 1 && parent.rchild != null) {
System.out.println("该节点已满,返回该已满的节点继续添加");
return parent.rchild;
} else {
try {
throw new Exception("节点无法再添加节点");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
public void CreateBiTree(BiTNode root, String data, int pos) {
}
// 前序遍历
public void Traversal1(BiTNode root) {
if (root != null) {
System.out.print(root.data + " ");
nodeNUM++;
Traversal1(root.lchild);
Traversal1(root.rchild);
}
}
}