* 步骤:
1、建立二叉树类BinarryTree
* 属性: 根节点 左子树 右子树
* 方法: 判断插入
* 中根遍历
* 2、中根遍历 递归找到叶子节点
*
*
* */
class Test4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = new int[] { 34, 53, 654, 765, 76, 1, 5, 6, 7, 2, 64, 43, 56 };
// 建立二叉树
BinarryTree tree = new BinarryTree(arr[0]);
for (int i = 0; i < arr.length; i++) {
BinarryTree.insert(tree, arr[i]);
}
//遍历
BinarryTree.order(tree);
}
}
class BinarryTree {
private int data;
private BinarryTree left;
private BinarryTree right;
BinarryTree(int data) { // 对象初始化
// TODO Auto-generated constructor stub
this.data = data;
this.left = null;
this.right = null;
}
// 构造子树
public static void insert(BinarryTree tree, int data) {
if (data <= tree.data) {
if (tree.left == null) {
tree.left = new BinarryTree(data); //建立左节点
} else {
insert(tree.left, data);
}
}
else {
if (tree.right == null) {
tree.right = new BinarryTree(data); //建立有节点
} else {
insert(tree.right, data);
}
}
}
public static void order(BinarryTree tree) {
if (tree != null) {
// 处理左子树和当前对象 【中根遍历】 :先左后中再右
order(tree.left);
System.out.print(tree.data + "-->");
order(tree.right);
}
}
}
|
|