
折纸的次数 —— 从上到下的折痕
本质上是中序遍历的问题,因为每一次在已有的折痕后折的时候,当前折痕上的折痕一定为凹,当前折痕下的折痕一定为凸 。实际模拟了一个不存在的二叉树结构的中序遍历。
注:折纸折几次整颗二叉树就有多少层
- package binarytree;
-
- public class PaperFolding {
-
- //i为当前层数,n为折纸次数
- //down==true为凹,down==false为凸
- public static void printProcess(int i, int n, boolean down) {
- if (i > n) {//整颗二叉树i==n
- return;
- }
-
- printProcess(i + 1, n, true);//凹
-
- //中序遍历,第二次遍历时打印
- if (down == true) {
- System.out.print("凹");
- } else {
- System.out.print("凸");
- }
-
- printProcess(i + 1, n, false);//凸
- }
-
-
- public static void main(String[] args) {
- int n = 3;
- printProcess(1, n, true);//从第一层开始,第一个折痕为凹痕
- }
-
- }