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

力扣988. 从叶结点开始的最小字符串

Problem: 988. 从叶结点开始的最小字符串

文章目录

  • 题目描述
  • 思路
  • 复杂度
  • Code

题目描述

在这里插入图片描述在这里插入图片描述在这里插入图片描述在这里插入图片描述

思路

遍历思想(利用二叉树的先序遍历)

先序遍历的过程中,用一个变量path拼接记录下其组成的字符串,当遇到根节点时再将其反转并比较大小(字典顺序大小)同时更新较小的结果字符串(其中要注意的操作是,字符串的反转与更新)

复杂度

时间复杂度:

O ( n ) O(n) O(n);其中 n n n为二叉树的节点个数

空间复杂度:

O ( h ) O(h) O(h);其中 h h h为二叉树的高度

Code

/*** Definition for a binary tree node.* public class TreeNode {*     int val;*     TreeNode left;*     TreeNode right;*     TreeNode() {}*     TreeNode(int val) { this.val = val; }*     TreeNode(int val, TreeNode left, TreeNode right) {*         this.val = val;*         this.left = left;*         this.right = right;*     }* }*/
class Solution {public String smallestFromLeaf(TreeNode root) {traverse(root);return res;}StringBuilder path = new StringBuilder();String res = null;private void traverse(TreeNode root) {if (root == null) {return;}if (root.left == null && root.right == null) {// Find the leaf node and compare the path// with the smallest lexicographic orderpath.append((char)('a' + root.val));// The resulting string is from leaf to root,// so inversion is requiredpath.reverse();String s = path.toString();if (res == null || res.compareTo(s) > 0) {res = s;}// Recover and properly maintain elements in pathpath.reverse();path.deleteCharAt(path.length() - 1);return;}path.append((char)('a' + root.val));traverse(root.left);traverse(root.right);path.deleteCharAt(path.length() - 1);}
}
http://www.lryc.cn/news/531437.html

相关文章:

  • 《PYTHON语言程序设计》(2018版)1.7近似π。利用步幅来进行修改
  • 低通滤波算法的数学原理和C语言实现
  • 【BUUCTF杂项题】荷兰宽带数据泄露、九连环
  • 安全策略实验报告
  • Haproxy+keepalived高可用集群,haproxy宕机的解决方案
  • 亚博microros小车-原生ubuntu支持系列:20 ROS Robot APP建图
  • Dockerfile构建容器镜像
  • python 在包含类似字符\x16、\x12、\x某某的数组中将以\x开头的字符找出来的方法
  • Spring Bean 的生命周期介绍
  • 调用腾讯云批量文本翻译API翻译srt字幕
  • 车载软件架构 --- 软件定义汽车面向服务架构的应用迁移
  • Baklib引领内容中台与人工智能技术的创新融合之路
  • 想品客老师的第十一天:模块化开发
  • 接入DeepSeek大模型
  • 基于遗传算法的256QAM星座图的最优概率整形matlab仿真,对比优化前后整形星座图和误码率
  • JavaScript系列(57)--工程化实践详解
  • Linux-CentOS的yum源
  • 【大数据技术】案例03:用户行为日志分析(python+hadoop+mapreduce+yarn+hive)
  • LeetCode 0680.验证回文串 II:两侧向中间,不同就试删
  • 第二十章 存储函数
  • 架构规划之任务边界划分过程中承接分配
  • 【C++】线程池实现
  • vsnprintf的概念和使用案例
  • 解读隐私保护工具 Fluidkey:如何畅游链上世界而不暴露地址?
  • Linux环境Kanass安装配置简明教程
  • 数据分析常用的AI工具
  • 项目中常用中间件有哪些?分别起什么作用?
  • kaggle视频行为分析1st and Future - Player Contact Detection
  • 1. junit5介绍
  • (脚本学习)BUU18 [CISCN2019 华北赛区 Day2 Web1]Hack World1