笔试题-构建非二叉树,且非递归遍历-利用栈

普通版本

package com.fang.恒天软件;import java.util.*;
import java.util.stream.Stream;public class Tree {TreeNode head;public Tree(TreeNode node) {this.head = node;}class ForeachNoMethodException extends Exception {public ForeachNoMethodException(String message) {super(message);}}private static final String EXCEPTION_MSG = "没有该遍历方式,请从【1(深度优先前序遍历所有)、2(深度优先前序遍历奇数)、3(深度优先前序遍历偶数)、" +"4(深度优先后序遍历所有)、5(深度优先后序遍历奇数)、6(深度优先后序遍历偶数)】";/*** 默认不传走顺序遍历*/public void foreach() {foreach(ForEachMethod.orderFrontMethod);}public void foreach(ForEachMethod method) {try {if (Stream.of("1", "2", "3").anyMatch(val -> val.equals(method.value))) {print(foreachFront(method));;} else if (Stream.of("4", "5", "6").anyMatch(val -> val.equals(method.value))) {print(foreachBack(method));} else {throw new ForeachNoMethodException(EXCEPTION_MSG);}} catch (ForeachNoMethodException ignored) {}}private void print(List<Integer> list) {list.forEach(val -> {if (list.indexOf(val) == list.size() - 1) {System.out.print(val);} else {System.out.print(val + " ");}});}/*** 前序遍历*/private List<Integer> foreachFront(ForEachMethod method) {List<Integer> result = new ArrayList<>();if (Objects.isNull(head)) {return result;}Stack<TreeNode> stack = new Stack<>();stack.push(head);while (!stack.empty()) {TreeNode node = stack.pop();if (Objects.equals(method, ForEachMethod.orderFrontMethod)) {result.add(node.value);} else if (Objects.equals(method, ForEachMethod.oddFrontMethod) && node.value % 2 != 0) {result.add(node.value);} else if (Objects.equals(method, ForEachMethod.evenFrontMethod) && node.value % 2 == 0) {result.add(node.value);}for (int i = node.nodes.size() - 1; i >= 0; i--) {stack.push(node.nodes.get(i));}}return result;}/*** 后序遍历*/private List<Integer> foreachBack(ForEachMethod method) {List<Integer> result = new ArrayList<>();if (Objects.isNull(head)) {return result;}Stack<TreeNode> stack = new Stack<>();stack.push(head);while (!stack.isEmpty()) {TreeNode cur = stack.pop();if (Objects.equals(method, ForEachMethod.orderBackMethod)) {result.add(cur.value);} else if (Objects.equals(method, ForEachMethod.oddBackMethod) && cur.value % 2 != 0) {result.add(cur.value);} else if (Objects.equals(method, ForEachMethod.evenBackMethod) && cur.value % 2 == 0) {result.add(cur.value);}for (TreeNode node : cur.nodes) {stack.push(node);}}Collections.reverse(result);return result;}/*** 非二叉树的节点*/static class TreeNode {Integer value;List<TreeNode> nodes;public TreeNode(Integer value, List<TreeNode> nodes) {this.value = value;this.nodes = nodes;}public TreeNode(Integer value) {this.value = value;this.nodes = new ArrayList<>();}}/*** 打印节点方式*/enum ForEachMethod {// 根 -> 左 -> 右orderFrontMethod("1", "深度优先前序遍历所有"),oddFrontMethod("2", "深度优先前序遍历奇数"),evenFrontMethod("3", "深度优先前序遍历偶数"),// 左 右 根orderBackMethod("4", "深度优先后序遍历所有"),oddBackMethod("5", "深度优先后序遍历奇数"),evenBackMethod("6", "深度优先后序遍历偶数");final String value;final String name;ForEachMethod(String value, String name) {this.value = value;this.name = name;}}}class Demo {public static void main(String[] args)  {List<Tree.TreeNode> treeNodes = new ArrayList<>();/***              1*           /  |  \*        2     3      4*      / | \  / \    / \*     5  6 7 8   9  10  11*/Tree.TreeNode node5 = new Tree.TreeNode(5);Tree.TreeNode node6 = new Tree.TreeNode(6);Tree.TreeNode node7 = new Tree.TreeNode(7);Tree.TreeNode node2 = new Tree.TreeNode(2, Arrays.asList(node5, node6, node7));Tree.TreeNode node8 = new Tree.TreeNode(8);Tree.TreeNode node9 = new Tree.TreeNode(9);Tree.TreeNode node3 = new Tree.TreeNode(3, Arrays.asList(node8, node9));Tree.TreeNode node10 = new Tree.TreeNode(10);Tree.TreeNode node11 = new Tree.TreeNode(11);Tree.TreeNode node4 = new Tree.TreeNode(4, Arrays.asList(node10, node11));Tree.TreeNode head = new Tree.TreeNode(1, Arrays.asList(node2, node3, node4));Tree tree = new Tree(head);tree.foreach(Tree.ForEachMethod.orderFrontMethod); // 1 2 5 6 7 3 8 9 4 10 11System.out.println();tree.foreach(Tree.ForEachMethod.oddFrontMethod); // 1 5 7 3 9 11System.out.println();tree.foreach(Tree.ForEachMethod.evenFrontMethod); // 2 6 8 4 10System.out.println("\n-----------------------------------------");tree.foreach(Tree.ForEachMethod.orderBackMethod); // 5 6 7 2 8 9 3 10 11 4 1System.out.println();tree.foreach(Tree.ForEachMethod.oddBackMethod); // 5 7 9 3 11 1System.out.println();tree.foreach(Tree.ForEachMethod.evenBackMethod); // 6 2 8 10 4}
}

使用策略模式

package com.fang.恒天软件;import java.util.*;public class Tree {TreeNode head;public Tree(TreeNode node) {this.head = node;}class ForeachNoMethodException extends Exception {public ForeachNoMethodException(String message) {super(message);}}private static final String EXCEPTION_MSG = "没有该遍历方式,请从【1(深度优先前序遍历所有)、2(深度优先前序遍历奇数)、3(深度优先前序遍历偶数)、" +"4(深度优先后序遍历所有)、5(深度优先后序遍历奇数)、6(深度优先后序遍历偶数)】";/*** 默认不传走顺序遍历*/public void foreach() {foreach(ForEachMethod.orderFrontMethod);}private void print(List<Integer> list) {list.forEach(val -> {if (list.indexOf(val) == list.size() - 1) {System.out.print(val);} else {System.out.print(val + " ");}});}public void foreach(ForEachMethod method) {ForEachFactory factory = new ForEachFactory();print(factory.getForEachWay(method).execute());}class ForEachFactory {Map<Tree.ForEachMethod, Tree.ForEachWay> forEachWayMap = new HashMap<>(16, 0.75F);public ForEachFactory() {registerForEachWay(ForEachMethod.orderFrontMethod, new FrontForEach(ForEachMethod.orderFrontMethod));registerForEachWay(ForEachMethod.oddFrontMethod, new FrontForEach(ForEachMethod.oddFrontMethod));registerForEachWay(ForEachMethod.evenFrontMethod, new FrontForEach(ForEachMethod.evenFrontMethod));registerForEachWay(ForEachMethod.orderBackMethod, new BackForEach(ForEachMethod.orderBackMethod));registerForEachWay(ForEachMethod.oddBackMethod, new BackForEach(ForEachMethod.oddBackMethod));registerForEachWay(ForEachMethod.evenBackMethod, new BackForEach(ForEachMethod.evenBackMethod));}private void registerForEachWay(Tree.ForEachMethod method, Tree.ForEachWay way) {forEachWayMap.put(method, way);}public Tree.ForEachWay getForEachWay(ForEachMethod method)  {try {if (forEachWayMap.containsKey(method)) {return forEachWayMap.get(method);} else {throw new ForeachNoMethodException(EXCEPTION_MSG);}} catch (ForeachNoMethodException e) {}return null;}}interface ForEachWay {List<Integer> execute();}class FrontForEach implements ForEachWay {ForEachMethod method;public FrontForEach(ForEachMethod method) {this.method = method;}@Overridepublic List<Integer> execute() {List<Integer> result = new ArrayList<>();if (Objects.isNull(head)) {return result;}Stack<TreeNode> stack = new Stack<>();stack.push(head);while (!stack.empty()) {TreeNode node = stack.pop();if (Objects.equals(method, ForEachMethod.orderFrontMethod)) {result.add(node.value);} else if (Objects.equals(method, ForEachMethod.oddFrontMethod) && node.value % 2 != 0) {result.add(node.value);} else if (Objects.equals(method, ForEachMethod.evenFrontMethod) && node.value % 2 == 0) {result.add(node.value);}for (int i = node.nodes.size() - 1; i >= 0; i--) {stack.push(node.nodes.get(i));}}return result;}}class BackForEach implements ForEachWay {ForEachMethod method;public BackForEach(ForEachMethod method) {this.method = method;}@Overridepublic List<Integer> execute() {List<Integer> result = new ArrayList<>();if (Objects.isNull(head)) {return result;}Stack<TreeNode> stack = new Stack<>();stack.push(head);while (!stack.isEmpty()) {TreeNode cur = stack.pop();if (Objects.equals(method, ForEachMethod.orderBackMethod)) {result.add(cur.value);} else if (Objects.equals(method, ForEachMethod.oddBackMethod) && cur.value % 2 != 0) {result.add(cur.value);} else if (Objects.equals(method, ForEachMethod.evenBackMethod) && cur.value % 2 == 0) {result.add(cur.value);}for (TreeNode node : cur.nodes) {stack.push(node);}}Collections.reverse(result);return result;}}/*** 非二叉树的节点*/static class TreeNode {Integer value;List<TreeNode> nodes;public TreeNode(Integer value, List<TreeNode> nodes) {this.value = value;this.nodes = nodes;}public TreeNode(Integer value) {this.value = value;this.nodes = new ArrayList<>();}}/*** 打印节点方式*/enum ForEachMethod {// 根 -> 左 -> 右orderFrontMethod("1", "深度优先前序遍历所有"),oddFrontMethod("2", "深度优先前序遍历奇数"),evenFrontMethod("3", "深度优先前序遍历偶数"),// 左 右 根orderBackMethod("4", "深度优先后序遍历所有"),oddBackMethod("5", "深度优先后序遍历奇数"),evenBackMethod("6", "深度优先后序遍历偶数");final String value;final String name;ForEachMethod(String value, String name) {this.value = value;this.name = name;}}}class Demo {public static void main(String[] args)  {List<Tree.TreeNode> treeNodes = new ArrayList<>();/***              1*           /  |  \*        2     3      4*      / | \  / \    / \*     5  6 7 8   9  10  11*/Tree.TreeNode node5 = new Tree.TreeNode(5);Tree.TreeNode node6 = new Tree.TreeNode(6);Tree.TreeNode node7 = new Tree.TreeNode(7);Tree.TreeNode node2 = new Tree.TreeNode(2, Arrays.asList(node5, node6, node7));Tree.TreeNode node8 = new Tree.TreeNode(8);Tree.TreeNode node9 = new Tree.TreeNode(9);Tree.TreeNode node3 = new Tree.TreeNode(3, Arrays.asList(node8, node9));Tree.TreeNode node10 = new Tree.TreeNode(10);Tree.TreeNode node11 = new Tree.TreeNode(11);Tree.TreeNode node4 = new Tree.TreeNode(4, Arrays.asList(node10, node11));Tree.TreeNode head = new Tree.TreeNode(1, Arrays.asList(node2, node3, node4));Tree tree = new Tree(head);tree.foreach(Tree.ForEachMethod.orderFrontMethod); // 1 2 5 6 7 3 8 9 4 10 11System.out.println();tree.foreach(Tree.ForEachMethod.oddFrontMethod); // 1 5 7 3 9 11System.out.println();tree.foreach(Tree.ForEachMethod.evenFrontMethod); // 2 6 8 4 10System.out.println("\n-----------------------------------------");tree.foreach(Tree.ForEachMethod.orderBackMethod); // 5 6 7 2 8 9 3 10 11 4 1System.out.println();tree.foreach(Tree.ForEachMethod.oddBackMethod); // 5 7 9 3 11 1System.out.println();tree.foreach(Tree.ForEachMethod.evenBackMethod); // 6 2 8 10 4}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/3526.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

面试:JVM垃圾回收

一、三种垃圾回收算法 1、标记清除&#xff08;已废弃&#xff09; 找到根对象&#xff08;局部变量正在引用的对象、静态变量正在引用的对象&#xff09;&#xff1b;沿着根对象的引用链&#xff0c;查看当前的对象是否被根对象所引用&#xff0c;若被引用&#xff0c;则加上…

区块链 | OpenSea 相关论文:Toward Achieving Anonymous NFT Trading(一)

​ &#x1f951;原文&#xff1a; Toward Achieving Anonymous NFT Trading &#x1f951;写在前面&#xff1a; 本文对实体的介绍基于论文提出的方案&#xff0c;而非基于 OpenSea 实际采用的方案。 其实右图中的 Alice 也是用了代理的&#xff0c;不过作者没有画出来。 正文…

机器视觉检测为什么是工业生产的刚需?

机器视觉检测在工业生产中被视为刚需&#xff0c;主要是因为它具备以下几个关键优势&#xff1a; 提高精度与效率&#xff1a;机器视觉系统可以进行高速、高精度的检测。这对于保证产品质量、减少废品非常关键。例如&#xff0c;在生产线上&#xff0c;机器视觉可以迅速识别产品…

UEFI安全启动模式下安装Ubuntu的NVIDIA显卡驱动

UEFI安全启动模式下安装ubuntu的nvidia显卡驱动 实践设备&#xff1a;华硕FX-PRO&#xff08;NVIDIA GeForce GTX 960M&#xff09; 一、NVIDIA官网下载驱动 1.1在浏览器地址栏输入https://www.nvidia.cn/drivers/lookup/进入网站&#xff0c;接着手动驱动搜索&#xff0c;并…

The Clock and the Pizza [NeurIPS 2023 oral]

本篇文章发表于NeurIPS 2023 (oral)&#xff0c;作者来自于MIT。 文章链接&#xff1a;https://arxiv.org/abs/2306.17844 一、概述 目前&#xff0c;多模态大语言模型的出现为人工智能带来新一轮发展&#xff0c;相关理论也逐渐从纸面走向现实&#xff0c;影响着人们日常生活…

探讨mfc100u.dll丢失的解决方法,修复mfc100u.dll有效方法解析

mfc100u.dll丢失是一个比较常见的情况&#xff0c;由于你电脑的各种操作&#xff0c;是有可能引起dll文件的缺失的&#xff0c;而mfc100u.dll就是其中的一个重要的dll文件&#xff0c;它的确实严重的话是会导致程序打不开&#xff0c;系统错误的。今天我们就来给大家科普一下mf…

太速科技-多路PCIe的阵列计算全国产化服务器

多路PCIe的阵列计算全国产化服务器 多路PCIe的阵列计算全国产化服务器以国产化处理器&#xff08;海光、飞腾ARM、算能RSIC V&#xff09;为主板&#xff0c;扩展6-8路PCIe3.0X4计算卡&#xff1b; 计算卡为全国产化的AI处理卡&#xff08;瑞星微ARM&#xff0c;算能AI&#x…

【stm32】swjtu西南交大嵌入式实验三 外部中断实验:按键中断

实验内容&#xff1a; 1、编写程序&#xff0c;设置主程序&#xff1a;跑马灯以 0.2s 的速度旋转&#xff1b;将 KB1 设置为外部中断&#xff0c;下 降沿触发&#xff0c;按下 KB1 则全彩灯的 R 灯闪烁 5 次。编译、下载程序到开发板&#xff0c;观察实 验现象&#xff1b;按下…

阶跃星辰:探索智能科技的星辰大海

引言 在当今快速发展的科技时代&#xff0c;人工智能已经成为推动社会进步的重要力量。阶跃星辰&#xff0c;正是在这一背景下诞生的。 阶跃星辰是一家专注于通用人工智能探索的公司&#xff0c;成立于2023年4月。该公司的创始团队由一群对人工智能充满热情和渴望的人组成&am…

LM1875L-TB5-T 音频功率放大器 PDF中文资料_参数_引脚图

LM1875L-TB5-T 规格信息&#xff1a; 商品类型音频功率放大器 音频功率放大器的类型- 输出类型1-Channel (Mono) 作业电压16V ~ 60V 输出功率25W x 1 4Ω 额外特性过流保护,热保护 UTC LM1875是一款单片功率放大器&#xff0c;可为消费类音频应 用提供极低失真和高品质的…

物联网鸿蒙实训解决方案

一、建设背景 在数字化浪潮汹涌的时代&#xff0c;华为鸿蒙系统以其前瞻的技术视野和创新的开发理念&#xff0c;成为了引领行业发展的风向标。 据华为开发者大会2023&#xff08;HDC. Together&#xff09;公布的数据&#xff0c;鸿蒙生态系统展现出了强劲的发展动力&#x…

MongoDB的UTCDateTime如何使用

使用MongoDB的UTCDateTime类来存储当前的UTC日期和时间。UTCDateTime对象在MongoDB中表示一个日期&#xff0c;但是它不是PHP的DateTime类。如果你想把UTCDateTime对象格式化为可读的字符串需要先把UTCDateTime对象转换成PHP的DateTime类 方法 (new MongoDB\BSON\UTCDateTime…

【论文浅尝】Phi-3-mini:A Highly Capable Language Model Locally on Your Phone

Phi-3-mini phi-3-mini&#xff0c;一个3.8亿个参数的语言模型&#xff0c;训练了3.3万亿个token&#xff0c;其总体性能&#xff0c;通过学术基准和内部测试进行衡量&#xff0c;可以与Mixtral 8x7B和GPT-3.5等模型相媲美(在MMLU上达到69%&#xff0c;在MT-bench上达到8.38)&…

深圳证券交易所Binary行情数据接口规范

对接深圳证券交易所Binary行情数据接口其实并不难&#xff0c;你需要具备以下知识。 1、需要了解Binary报文设计结构&#xff0c;消息头消息体消息尾。 消息体&#xff1a; 如果是纯map结构的比较简单&#xff0c;字段平铺开来即可。如{"id":"1","…

WEB服务的配置与使用 Apache HTTPD

服务端&#xff1a;服务器将发送由状态代码和可选的响应正文组成的 响应 。状态代码指示请求是否成功&#xff0c;如果不成功&#xff0c;则指示存在哪种错误情况。这告诉客户端应该如何处理响应。较为流星的web服务器程序有&#xff1a; Apache HTTP Server 、 Nginx 客户端&a…

bugfix: com.alibaba.druid.sql.parser.EOFParserException: EOF

前言 在日常的开发工作中&#xff0c;我们经常会遇到各种各样的问题&#xff0c;其中涉及数据库操作的接口联调尤其容易出现意想不到的状况。今天我就遇到了一个关于Druid SQL解析异常的问题&#xff0c;具体表现为com.alibaba.druid.sql.parser.EOFParserException: EOF。通过…

基于SpringBoot开发的同城租房系统租房软件APP小程序源码

项目背景 一、市场前景 随着城市化进程的加快和人口流动性的增强&#xff0c;租房市场正逐渐成为一个不可忽视的巨大市场。传统的租房方式往往存在着信息不对称、效率低下等问题&#xff0c;而同城租房软件的出现&#xff0c;则有效地解决了这些问题&#xff0c;为租房市场注…

k8s日常动手实践 ~~ pod访问 pod请求 k8s api ~ 含新版带curl的busybox镜像

前言&#xff1a; 可以使用 Kubernetes API 获取集群信息。使用 Service Account&#xff08;SA&#xff09;进行身份验证&#xff0c;可以以安全的方式访问 Kubernetes API&#xff0c;而无需在 Pod 中使用明文凭据。 以下是一个使用 Service Account 访问 Kubernetes API 获…

每日OJ题_DFS回溯剪枝①_力扣46. 全排列(回溯算法简介)

目录 回溯算法简介 力扣46. 全排列 解析代码 回溯算法简介 回溯算法是一种经典的递归算法&#xff0c;通常⽤于解决组合问题、排列问题和搜索问题等。 回溯算法的基本思想&#xff1a;从一个初始状态开始&#xff0c;按照⼀定的规则向前搜索&#xff0c;当搜索到某个状态无…

【韩国】UE5的MetaHuman确实可以导入Blender进行编辑。

UE5的MetaHuman确实可以导入Blender进行编辑。根据网络上的信息&#xff0c;你可以将MetaHuman模型导出为FBX文件&#xff0c;然后在Blender中进行修改。修改完成后&#xff0c;你可以将其重新导入到Unreal Engine 5中4。请注意&#xff0c;当你在Blender中编辑模型时&#xff…