中序遍历:先访问每个节点的左孩子,再访问节点本身,最后访问节点的右孩子
递归实现
public static void midOrder(BinaryTree root) {
if (root == null)
throw new IllegalArgumentException("请输入一棵树!");
if (root.getLeft() != null) {
midOrder(root.getLeft());
}
System.out.print(root.getData()+"\t");
if (root.getRight() != null) {
midOrder(root.getRight());
}
}
用栈实现
public static void inOrderUnRecur(BinaryTree root) {
if (root != null) {
Stack<BinaryTree> stack = new Stack<>();
while (!stack.isEmpty() || root != null) {
if (root != null) {
stack.push(root);
root = root.getLeft();
} else {
root = stack.pop();
System.out.print(root.getData()+"\t");
root = root.getRight();
}
}
}
System.out.println();
}
空间复杂度都是树的深度