package tree2;import java.util.LinkedList;
import java.util.Queue;public class PagerFoldingTest{public static void main(String[] args){//模拟折纸过程,产生树Node<String> tree = createTree(3);//遍历树,打印每个结点printTree(tree);}//通过模拟对折N次纸,产生树public static Node<String> createTree(int N){//定义根结点Node<String> root = null;for(int i=0; i<N; i++){//第一次对折if(i==0){root = new Node<>("down", null, null);//continue语句用于循环语句中,作用是不执行循环体剩余部分,直接进行下次循环。continue;}//非第一次对折//关键:通过层序遍历的思想,找到叶子节点,给叶子节点添加子节点Queue<Node> queue = new LinkedList<>();queue.offer(root);//循环遍历队列while(!queue.isEmpty()){Node temp = ve();if(temp.left!=null){queue.offer(temp.left);}if(temp.right!=null){queue.offer(temp.right);}//判断当前节点是不是叶子节点if(temp.left==null && temp.right==null){temp.left = new Node("down",null,null);temp.right = new Node("up",null,null);}}}return root;}//中序遍历打印public static void printTree(Node root){if(root==null){return;}if(root.left!=null){printTree(root.left);}System.out.print(root.item+" ");if(root.right!=null){printTree(root.right);}}private static class Node<T>{//T是自定义泛型,泛型的主要目的是实现 java的类型安全,消除了强制类型转换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;}}
}
本文发布于:2024-02-02 14:27:11,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170685523044407.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |