二叉树经典问题--折纸问题

二叉树经典问题–折纸问题
请把纸条竖着放在桌⼦上,然后从纸条的下边向上⽅对折,压出折痕后再展 开。此时有1条折痕,突起的⽅向指向纸条的背⾯,这条折痕叫做“下”折痕 ;突起的⽅向指向纸条正⾯的折痕叫做“上”折痕。如果每次都从下边向上⽅ 对折,对折N次。请从上到下计算出所有折痕的⽅向。
实现

public class PagerFoldingTest {
    public static void main(String[] args) {
        Node<String> tree=createTree(2);
        printTree(tree);
    }
    public static Node<String> createTree(int N){
        Node<String> root=null;
        for (int i = 0; i < N; i++) {
            if(i==0){
                root=new Node<String>("down",null,null);
                continue;
            }
            MyQueue<Node> queue = new MyQueue<Node>();
            queue.enqueue(root);
            while(!queue.isEmpty()){
                Node tmp = queue.dequeue();
                if(tmp.left!=null){
                    queue.enqueue(tmp.left);
                }
                if(tmp.right!=null){
                    queue.enqueue(tmp.right);
                }
                if(tmp.left==null&&tmp.right==null){
                    tmp.left=new Node("down",null,null);
                    tmp.right=new Node("up",null,null);
                }
            }
        }
        return root;
    }
    public static void printTree(Node<String> root){
        if(root==null){
            return ;
        }
        if(root.left!=null){
            printTree(root.left);
        }
        System.out.print(root.item+" ");
        if(root.right!=null){
            printTree(root.right);
        }
    }
    public static class Node<T>{
        public T item;
        public Node left;
        public Node right;

        public Node(T item, Node left, Node right) {
            this.item = item;
            this.left = left;
            this.right = right;
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值