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

力扣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 order
            path.append((char)('a' + root.val));
            // The resulting string is from leaf to root,
            // so inversion is required
            path.reverse();
            String s = path.toString();
            if (res == null || res.compareTo(s) > 0) {
                res = s;
            }

            // Recover and properly maintain elements in path
            path.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.kler.cn/a/531991.html

相关文章:

  • 模拟实战-用CompletableFuture优化远程RPC调用
  • 基于Kamailio、MySQL、Redis、Gin、Vue.js的微服务架构
  • LeetCode 3105. Longest Strictly Increasing or Strictly Decreasing Subarray
  • 注解(Annotation)
  • Leetcode 8283 移除排序链表中的重复元素
  • 六十分之三十七——一转眼、时光飞逝
  • 【深度学习】图像识别模型与训练策略
  • 63.视频推荐的算法|Marscode AI刷题
  • 时序论文37 | DUET:双向聚类增强的多变量时间序列预测
  • 小书包:让阅读更美的二次开发之作
  • Springboot整合Redis客户端
  • 2025.2.2牛客周赛 Round 79 IOI
  • 手写MVVM框架-构建虚拟dom树
  • 在Vue3 + Vite 项目中使用 Tailwind CSS 4.0
  • 多线程创建方式三:实现Callable接口
  • WireShark4.4.2浏览器网络调试指南:偏好设置下(十)
  • SpringBoot+Mybatis整合Mysql数据库的Demo
  • 《黑马点评》实战笔记
  • Qwen2.5-Max:AI技术的新里程碑
  • 力扣 55. 跳跃游戏
  • 【OS】AUTOSAR架构下的Interrupt详解(下篇)
  • Verilog基础(五):时序逻辑
  • 【贪心算法篇】:“贪心”之旅--算法练习题中的智慧与策略(三)
  • 【C++】B2124 判断字符串是否为回文
  • 50【Windows与Linux】
  • 【C++】string类(上):string类的常用接口介绍