【无标题】

记录

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)

相关推荐
幽络源小助理几秒前
懒人美食帮SpringBoot订餐系统开发实现
java·spring boot·后端·美食
Cuit小唐3 分钟前
C++ 模板方法模式详解
java·c++·模板方法模式
吗喽对你问好8 分钟前
华为5.7机考第一题充电桩问题Java代码实现
java·华为·排序
胡斌附体8 分钟前
设置环境变量启动jar报
java·jar·cmd·path
源码云商2 小时前
基于Spring Boot + Vue的母婴商城系统( 前后端分离)
java·spring boot·后端
冼紫菜5 小时前
【Spring Boot 多模块项目】@MapperScan失效、MapperScannerConfigurer 报错终极解决方案
java·开发语言·mybatis
还听珊瑚海吗6 小时前
基于SpringBoot的抽奖系统测试报告
java·spring boot·后端
练习本6 小时前
Android系统架构模式分析
android·java·架构·系统架构
心灵宝贝8 小时前
IDEA 安装 SpotBugs 插件超简单教程
java·macos·intellij-idea
幼稚诠释青春8 小时前
Java学习笔记(对象)
java·开发语言