public class BinaryTree {
// 创建二叉树的方法
public TreeNode createTree(int[] value) {
//List<TreeNode> list = new ArrayList<>();
LinkedList<TreeNode> list = new LinkedList<>();
for (int i = 0; i < value.length; i++) {
TreeNode node = new TreeNode(value[i]);
list.add(node);
}
TreeNode root;
for (int i = 0; i < list.size() / 2; i++) {
root = list.get(i);
TreeNode left = list.get(2 * i + 1);
root.left = left;
if (2 * i + 2 < list.size()) {
TreeNode right = list.get(2 * i + 2);
root.right = right;
}
}
return list.get(0);
}
// 前序遍历
public void preOrder(TreeNode root) {
if (root != null) {
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
}
// 中序遍历
public void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
// 后序遍历
public void postOrder(TreeNode root) {
if (root != null) {
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val + " ");
}
}
public static void main(String[] args) {
int[] value = new int[]{1, 2, 3, 4, 5};
BinaryTree tree = new BinaryTree();
TreeNode root = tree.createTree(value);
System.out.println("前序遍历:");
tree.preOrder(root);
System.out.println();
System.out.println("中序遍历:");
tree.inOrder(root);
System.out.println();
System.out.println("后序遍历:");
tree.postOrder(root);
}
}
层序遍历1
// 层序遍历:用队列实现
public static List<Integer> levelOrder(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode cur = queue.poll();
res.add(cur.val);
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
return res;
}
层序遍历2
public static List<List<Integer>> levelOrder2(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Deque<TreeNode> queue = new ArrayDeque<>();
if (root != null) {
queue.offer(root);
}
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> result = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
result.add(cur.val);
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
res.add(result);
}
return res;
}