【无标题】

记录

2025.4.19

题目:

思路:

按照访问左子树------根节点------右子树的方式遍历这棵树

解题步骤:

定义 inorder(root) 表示当前遍历到 root 节点的答案,那么按照定义,我们只要递归调用 inorder(root.left) 来遍历 root 节点的左子树,然后将 root 节点的值加入答案,再递归调用inorder(root.right) 来遍历 root 节点的右子树即可,递归终止的条件为碰到空节点。

代码:

java 复制代码
/**
 * 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 List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        inorder(root, res);
        return res;
    }

    public void inorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }
}

复杂度:

N(N)

N(N)

相关推荐
某不知名網友7 小时前
C++ 深浅拷贝:从默认拷贝到 Rule of Five
java·开发语言
青山木7 小时前
Hot 100 --- 划分字母区间
java·数据结构·算法·leetcode·贪心算法
Zzzzmo_7 小时前
SpringBoot 配置文件
java·spring boot
君顾17 小时前
外卖CPS小程序开发实战指南:从零到上线的完整流程
java·开发语言·外卖
無a伟7 小时前
RabbitMq高级特性:消息确认,持久化,重试机制
java·分布式·rabbitmq
流烟默7 小时前
xxl-job 接入 Spring 的两种方式:手动装配与自动装配(含 initMethod 双启动踩坑实录)
java·spring·xxl-job
鹅城剑仙7 小时前
Spring Boot 3 全局异常处理与统一响应封装进阶实战
java·spring boot·后端
橘子汽水1687 小时前
Leetcode 208,207实现Trie前缀树,课程表
java·数据结构·算法·leetcode
tryxr7 小时前
Chat2Excel 文件服务模块剩余功能开发
java·服务器·windows·java项目·文件服务
张小姐的猫7 小时前
【AI大模型接入SDK】 —— Ollama本地接入Deepseek
java·linux·开发语言·网络·c++·人工智能