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

编程导航算法村第七关 |二叉树的遍历

编程导航算法村第七关 | 二叉树的遍历

前序遍历(递归)

 public List<Integer> preorderTraversal(TreeNode root) {ArrayList<Integer> result = new ArrayList<Integer>();preorder(root, result);return result;}public void preorder(TreeNode root, List<Integer> result) {if (root == null) {return;}result.add(root.val);preorder(root.left, result);preorder(root.right, result);}

前序遍历(迭代)

  • 先迭代到树的最底层,左左端的元素,然后弹出栈,访问他的右节点
 public List<Integer> preorderTraversal(TreeNode root) {ArrayList<Integer> result = new ArrayList<Integer>();if (result == null) {return result;}Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode node = root;while (!stack.isEmpty() || node != null) {while (node!= null) {result.add(node.val);stack.push(node);node = node.left;}node = stack.pop();node = node.right;}return result;}

中序遍历(迭代)

 public List<Integer> inorderTraversal(TreeNode root) {ArrayList<Integer> result = new ArrayList<>();if (root == null) {return result;}Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode node = root;while (!stack.isEmpty() || node != null) {while (node != null) {stack.push(node);node = node.left;}node = stack.pop();result.add(node.val);node = node.right;}return result;}

后续遍历(反转法)

  • 后续遍历相当于在前序遍历的基础上,先访问右节点再访问左节点,最后翻转
 public List<Integer> postorderTraversal(TreeNode root) {ArrayList<Integer> result = new ArrayList<>();if (root == null) {return result;}Stack<TreeNode> stack = new Stack<TreeNode>();TreeNode node = root;while (!stack.isEmpty() || node != null) {while (node != null) {stack.push(node);result.add(node.val);node = node.right;}node = stack.pop();node = node.left;}Collections.reverse(result);return result;}
http://www.lryc.cn/news/109487.html

相关文章:

  • 【docker】docker-compose安装带ui页面的kafka集群
  • java实现多级菜单
  • HTML中元素和标签有什么区别?
  • android 如何分析应用的内存(十三)——perfetto
  • Chapter20 音乐
  • 详解Nodejs中的模块化
  • debug思路 - maven构建报错
  • DSP学习笔记
  • Java中的Apache Commons Math是什么?
  • 规划路线(微信小程序、H5)
  • 【CSS】视频文字特效
  • linux-MySQL的数据目录
  • AI绘图实战(十二):让AI设计LOGO/图标/标识 | Stable Diffusion成为设计师生产力工具
  • 机器视觉系统设计:基础知识
  • C# Blazor 学习笔记(11):路由跳转和信息传值
  • Centos 7 安装 Python 时 zlib not available 错误解决
  • python sqllite基本操作
  • 记录--基于css3写出的流光登录(注释超详细!)
  • 【测试设计】性能测试工具选择:wrk?jmeter?locust?还是LR?
  • 为什么升级JDK 11后堆外内存使用增长了?
  • Vue自定义防重复点击指令(v-repeatClick)
  • 高频高速板行业现状及市场前景
  • 【练手】自定义注解+AOP
  • QComboBox添加样式后,编辑栏背景一直白色问题解决方法。
  • vue动态绑定多个class以及带上三元运算或其他条件
  • Rpc原理
  • yapi容器化docker部署以及mongodb容器的持久化挂载异常问题
  • MyBatis-XML映射文件
  • C++类和对象入门(下)
  • 安卓:实现复制粘贴功能