package com.cb.java.algorithms.jianzhioffer.tree;
import java.util.ArrayList;
import java.util.List;
public class BinaryTree<E> {
public static class Node<E> {
Node<E> left = null; // 左子树
Node<E> right = null; // 右子树
E data = null; // 数据
public Node(E data) {
this.data = data;
this.left = null;
this.right = null;
}
public Node() {
}
}
private Node<E> root = null; // 根节点
private List<Node<E>> list = null; // 节点列表,用于将数组元素转化为节点
public Node<E> getRoot() {
return this.root;
}
public void createTreeByArray(Object[] array) {
this.list = new ArrayList<>();
// 将数组添加到节点列表
for (int i = 0; i < array.length; i++) {
list.add(new Node<>((E) array[i]));
}
System.out.println("头节点->" + list.get(0).data);
this.root = new Node<>(list.get(0).data);
// 为二叉树指针赋值
for (int j = 0; j < (list.size() / 2); j++) {
try {
// 为左子树赋值 j*2+1
list.get(j).left = list.get(j * 2 + 1);
System.out.println("节点" + list.get(j).data + "左子树:" + list.get(j * 2 + 1).data);
list.get(j).right = list.get(j * 2 + 2);
System.out.println("节点" + list.get(j).data + "右子树:" + list.get(j * 2 + 2).data);
} catch (Exception e) {
// TODO: handle exception
}
}
}
/**
* 先序遍历二叉树
*
* @param root
*/
public void inOrder(Node<E> root) {
if (root == null) {
return;
}
System.out.println(root.data);
inOrder(root.left); // 递归输出左子树
inOrder(root.right); // 递归输出右子树
}
/**
* 中序遍历二叉树
*
* @param root
*/
public void inOrderTraversal(Node<E> root) {
if (root == null) {
return;
}
inOrderTraversal(root.left);
System.out.println(root.data);
inOrderTraversal(root.right);
}
/**
* 后续遍历
*
* @param root
*/
public void postOrder(Node<E> root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.println(root.data);
}
public static void main(String[] args) {
BinaryTree<Integer> binaryTree = new BinaryTree<>();
Object[] arrays = { new Integer(1), new Integer(2), new Integer(3), new Integer(4), 5, 6, 7, 8, 9, 10 };
binaryTree.createTreeByArray(arrays);
;
binaryTree.inOrder(binaryTree.list.get(0));
}
}
转自:https://www.cnblogs.com/liaohai/archive/2017/03/08/6523069.html