import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.LinkedBlockingQueue; /** * Created by itworker365 on 5/10/2017. */ public class BinaryTree { public static void main (String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(1); list.add(2); list.add(3); list.add(4); list.add(5); list.add(6); list.add(7); BinaryTree bt = new BinaryTree(); TreeNode tree = bt.buildTreeAsList(list, null, 0); bt.printTreeLevelTrace(tree); } /** * 按照LIST顺序构建完全二叉树 * */ public TreeNode buildTreeAsList (List<Integer> list, TreeNode root, int pos) { if (root == null) { root = new TreeNode(list.get(0), null, null); } int listSize = list.size(); int leftPos = pos * 2 + 1; int rightPos = pos * 2 + 2; if (pos == listSize) { return root; } else { // build left if (leftPos < listSize) { TreeNode nodeLeft = new TreeNode(list.get(leftPos), null, null); root.setLeft(nodeLeft); buildTreeAsList(list, nodeLeft, leftPos); } // build right if (rightPos < listSize){ TreeNode nodeRight = new TreeNode(list.get(rightPos), null, null); root.setRight(nodeRight); buildTreeAsList(list, nodeRight, rightPos); } } return root; } // 前序遍历, 根-》左-》右 private void printTreePreOrderRec (TreeNode root) { if (root != null) { System.out.println(root.value); printTreePreOrderRec(root.getLeft()); printTreePreOrderRec(root.getRight()); } } // 中序遍历, 左-》根-》右 private void printTreeMidOrderRec (TreeNode root) { if (root != null) { printTreeMidOrderRec(root.getLeft()); System.out.println(root.value); printTreeMidOrderRec(root.getRight()); } } // 后序遍历, 左-》右-》根 private void printTreePostOrderRec (TreeNode root) { if (root != null) { printTreePostOrderRec(root.getLeft()); printTreePostOrderRec(root.getRight()); System.out.println(root.value); } } // 层序遍历 private void printTreeLevelTrace (TreeNode root) { Queue<TreeNode> queue = new LinkedBlockingQueue<>(); if (root == null) { return; } queue.add(root); while (!queue.isEmpty()) { TreeNode node = queue.poll(); System.out.println(node.getValue()); if (node.getLeft() != null) { queue.offer(node.getLeft()); } if (node.getRight() != null) { queue.offer(node.getRight()); } } } // 只打印叶子结点 private void printTreeLefeRec (TreeNode root) { if (root.getLeft() == null || root.getRight() == null) { System.out.println(root.getValue()); } else { printTreeMidOrderRec(root.getLeft()); printTreeMidOrderRec(root.getRight()); } } static class TreeNode { int value; TreeNode left; TreeNode right; public TreeNode(int value, TreeNode left, TreeNode right) { this.value = value; this.left = left; this.right = right; } public int getValue() { return value; } public void setValue(int value) { this.value = value; } public TreeNode getLeft() { return left; } public void setLeft(TreeNode left) { this.left = left; } public TreeNode getRight() { return right; } public void setRight(TreeNode right) { this.right = right; } } }