当前位置: 首页 > news >正文

力扣 LeetCode 144. 二叉树的前序遍历(Day6:二叉树)

解题思路:

方法一:递归(中左右)

class Solution {List<Integer> res = new ArrayList<>();public List<Integer> preorderTraversal(TreeNode root) {recur(root);return res;}public void recur(TreeNode root) {if (root == null) return;res.add(root.val);recur(root.left);recur(root.right);}
}

方法二:迭代(非递归法)

也就是用栈

重点弄懂前序是怎么用栈来实现的(以前序为基准,推出后序和中序)

因为栈是先进后出,所以实现前序,是中右左,先放右节点,再放左节点

后序迭代的推导:

正常情况下,前序是中左右(迭代法时栈用中右左),后序是左右中,那么:

中左右->中右左->左右中

先交换语句,再整体调用Collections.reverse(),就可以得到后序的迭代法

本题为前序迭代:

class Solution {public List<Integer> preorderTraversal(TreeNode root) {Deque<TreeNode> stack = new ArrayDeque<>();List<Integer> res = new ArrayList<>();if (root == null) return res;stack.push(root);while (!stack.isEmpty()) {//前面判断过了,所以此时 node 必不为空TreeNode node = stack.pop();res.add(node.val);if (node.right != null) stack.push(node.right);if (node.left != null) stack.push(node.left);}return res;}
}

http://www.lryc.cn/news/486430.html

相关文章:

  • Adobe Illustrator(Ai)修图软件入门操作参考,收集查过的各个细节用法
  • Apache Paimon、Apache Hudi、Apache Iceberg对比分析
  • [ 网络安全介绍 5 ] 为什么要学习网络安全?
  • 生产环境centos8 Red Hat8部署ansible and 一键部署mysql两主两从ansible脚本预告
  • 华为云stack网络服务流量走向
  • 嵌入式硬件杂谈(二)-芯片输入接入0.1uf电容的本质(退耦电容)
  • 计算机网络HTTP——针对实习面试
  • JAVA中对象实体与对象引用有何不同?举例说明
  • C++设计思想-001-设计模式-单例模式
  • 远程连接服务器
  • 【分布式技术】ES扩展知识-Elasticsearch分词器的知识与选择
  • 【网络安全 | 漏洞挖掘】通过密码重置污染实现账户接管
  • 【Nginx从入门到精通】01 、教程简介
  • MySQL面试之底层架构与库表设计
  • C2 追踪器:监控指挥与控制的重要性
  • 二、神经网络基础与搭建
  • java导出pdf
  • muduo之线程同步CountDownLatch
  • 【Python系列】Python中打印详细堆栈信息的技巧
  • SpringBoot中监听器、过滤器、拦截器和AOP详解
  • 如何让手机ip变成动态
  • [Qt platform plugin问题] Could not load the Qt platform plugin “xcb“
  • 嵌入式开发人员如何选择合适的开源前端框架进行Web开发
  • MySQL数据库(七)----查询相关操作(子查询)
  • 01_Spring开胃菜
  • SpringBoot使用AspectJ的@Around注解实现AOP全局记录接口:请求日志、响应日志、异常日志
  • WPF下播放Rtmp的解决方案
  • 7.高可用集群架构Keepalived双主热备原理
  • 为以人工智能为中心的工作负载重新设计的全局控制台
  • go channel中的 close注意事项 range取数据