zoukankan      html  css  js  c++  java
  • 二叉树解决折纸方向问题

    问题:对折纸,永远从同一个方向对折,输出对折N次后每个折痕的朝向。

     算法:

     1 package io.guangsoft;
     2 
     3 import java.util.LinkedList;
     4 import java.util.PriorityQueue;
     5 import java.util.Queue;
     6 
     7 public class FoldAlgorithm {
     8     //节点类
     9     private static class Node<T> {
    10         public T item;
    11         public Node left;
    12         public Node right;
    13         public Node(T item, Node left, Node right) {
    14             this.item = item;
    15             this.left = left;
    16             this.right = right;
    17         }
    18     }
    19     //模拟对折N次纸,产生树
    20     public static Node<String> createNode(int n) {
    21         //定义根节点
    22         Node<String> root = null;
    23         for(int i = 0; i < n; i++) {
    24             //如果为第一次对折,创建根节点
    25             if(i == 0) {
    26                 root = new Node("down", null, null);
    27                 continue;
    28             }
    29             //定义一个辅助队列,通过层序遍历思想,找到叶子节点,叶子结点添加叶子结点
    30             Queue<Node> queue = new LinkedList<>();
    31             queue.offer(root);
    32             //循环遍历队列
    33             while(!queue.isEmpty()) {
    34                 //从队列弹出一个节点
    35                 Node tmp = queue.poll();
    36                 //如果有左子节点,则把左子节点放入队列
    37                 if(tmp.left != null) {
    38                     queue.offer(tmp.left);
    39                 }
    40                 //如果有右子节点,则把右子节点放入队列
    41                 if(tmp.right != null) {
    42                     queue.offer(tmp.right);
    43                 }
    44                 //如果同时没有左子节点和右子节点,那么该节点为叶子结点,只需要给该节点添加左子节点和右子节点即可
    45                 if(tmp.left == null && tmp.right == null) {
    46                     tmp.left = new Node("down", null, null);
    47                     tmp.right = new Node("up", null, null);
    48                 }
    49             }
    50         }
    51         return root;
    52     }
    53     //中序遍历树
    54     public static void printTree(Node<String> root) {
    55         if(root == null) return;
    56         //打印左子树的每个节点
    57         if(root.left != null) {
    58             printTree(root.left);
    59         }
    60         //输出当前节点
    61         System.out.printf("%4s	", root.item );
    62         //打印当前节点
    63         if(root.right != null) {
    64             printTree(root.right);
    65         }
    66     }
    67     //主类
    68     public static void main(String args[]) {
    69         printTree(createNode(3));
    70     }
    71 }

     结果:

  • 相关阅读:
    stark
    MySQL与JDBC
    存储过程/视图/触发器
    MyCat部署运行(Windows环境)与使用步骤详解
    常用单词总结
    表单校验---validation检验
    jQuery简介
    javascript简单介绍
    HTML&&CSS
    消息队列Java的简单实现
  • 原文地址:https://www.cnblogs.com/guanghe/p/13630491.html
Copyright © 2011-2022 走看看