今天又复习了树的一些特点 ..
虽然在数据结构上有接触过.不过都是用c++实现的,现在用java来实现反而有点不大习惯.
只写了个通过数组来构造一棵树的几个方法.中序遍历树之后排列出来的数字都是有序的..
public TreeNode ArrayToTree(int[] array) {
if (array == null) {
throw new RuntimeException("传入的数组为空");
}
TreeNode root = new TreeNode(array[0]);
int i = 0;
for (i = 1; i < array.length; i++) {
toTree(array[i], root);
}
return root;
}
/**
* 递归将每个结点插入树中
*
* @param i结点中的数据
* @param t树的根结点
*/
public void toTree(int i, TreeNode t) {
if (t != null) {
// 左右子树都为空的时候则必定新建结点插入
if (t.getLchild() == null && t.getRchild() == null) {
if (i < (Integer) t.getData()) {
t.setLchild(new TreeNode(i));
} else {
t.setRchild(new TreeNode(i));
}
// 左右子树只有一边为空时,当其满足条件则新建结点插入,否则递归判断
} else if (t.getLchild() == null && t.getRchild() != null) {
if (i < (Integer) t.getData()) {
t.setLchild(new TreeNode(i));
} else {
toTree(i, t.getRchild());
}
} else if (t.getLchild() != null && t.getRchild() == null) {
if (i >= (Integer) t.getData()) {
t.setRchild(new TreeNode(i));
} else {
toTree(i, t.getLchild());
}
// 左右子树均存在的情况下,递归..
} else if (i < (Integer) t.getData()) {
toTree(i, t.getLchild());
} else if (i >= (Integer) t.getData()) {
toTree(i, t.getRchild());
}
}
}