问题描述
请把一段纸条竖着放在桌子上,然后从纸条的下边向上方对折1次,压出折痕后展开。此时 折痕是凹下去的,即折痕突起的方向指向纸条的背面。如果从纸条的下边向上方连续对折2 次,压出折痕后展开,此时有三条折痕,从上到下依次是下折痕、下折痕和上折痕。
给定一 个输入参数N,代表纸条都从下边向上方连续对折N次,请从上到下打印所有折痕的方向 例如:N=1时,打印: down;N=2时,打印: down down up
分析
我们把对折后的纸张翻过来,让粉色朝下,这时把第一次对折产生的折痕看做是根结点,那第二次对折产生的下折痕就是该结点的左子结点,而第二次对折产生的上折痕就是该结点的右子结点,这样我们就可以使用树型数据结构来描述对折后产生的折痕。
这棵树有这样的特点:
- 根结点为下折痕;
- 每一个结点的左子结点为下折痕;
- 每一个结点的右子结点为上折痕。
解题(Java)
public class PaperFolding {
//定义结点类
private static class Node {
String item;
Node left;
Node right;
public Node(String item, Node left, Node right) {
this.item = item;
this.left = left;
this.right = right;
}
}
//构建深度为N的折痕树
private static Node createTree(int N) {
Node root = null;
for (int i=1; i<=N; i++) {
if(i==1) {
//第一次对折,只有一条折痕,创建根结点
root = new Node("down", null, null);
} else {
//如果不是第一次对折,则使用队列保存根结点
Deque<Node> queue = new LinkedList<>();
queue.offer(root);
//循环遍历队列
while(!queue.isEmpty()) {
//从队列中拿出一个结点
Node tmp = queue.poll();
//如果左子结点不为空,把左子结点添加到队列中
if (tmp.left!=null) {
queue.offer(tmp.left);
}
//如果右子结点不为空,把右子节点添加到队列中
if (tmp.right!=null) {
queue.offer(tmp.right);
}
//如果当前节点的左子结点和右子结点都为空,为当前结点创建一个值为down的左子结点,一个值为up的右子结点
if (tmp.left==null && tmp.right==null) {
tmp.left = new Node("down",null,null);
tmp.right = new Node("up",null,null);
}
}
}
}
return root;
}
//使用中序遍历,打印出树中所有结点的内容
private static void printTree(Node tree) {
if (tree==null) {
return;
}
printTree(tree.left);
System.out.println(tree.item);
printTree(tree.right);
}
// 主函数
public static void main(String[] args) {
Node tree = createTree(3);
printTree(tree);
}
}
down
down
up
down
down
up
up