58同城高频编程考题:二叉树的中序遍历(简单)

题目描述

给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

示例 1:

输入:root = [1,null,2,3]
输出:[1,3,2]

示例 2:输入:root = [] 输出:[]

示例 3:输入:root = [1] 输出:[1]

提示:

  • 树中节点数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

解题思路

中序遍历的顺序是:

  1. 先遍历左子树
  2. 然后访问根节点
  3. 最后遍历右子树

要实现二叉树的中序遍历,最常见的方式是使用递归。

import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        inorder(root, result);
        return result;
    }

    private void inorder(TreeNode node, List<Integer> result) {
        if (node == null) {
            return;
        }
        // 先递归遍历左子树
        inorder(node.left, result);
        // 然后访问根节点
        result.add(node.val);
        // 最后递归遍历右子树
        inorder(node.right, result);
    }
}

迭代方法使用栈来替代递归。具体步骤如下:

  1. 从根节点开始,沿着左子树不断往下走,把所有节点压入栈中。
  2. 当没有左子树时,弹出栈顶节点,访问该节点,然后处理该节点的右子树。

复杂度分析

  • 时间复杂度:O(n),其中 n 是二叉树的节点数,因为每个节点都恰好被遍历一次。
  • 空间复杂度:O(h),其中 h 是二叉树的高度。栈的空间开销取决于树的高度,最坏情况下(退化为链表),空间复杂度为 O(n)。

代码实现

package org.zyf.javabasic.letcode.hot100.tree;

import org.zyf.javabasic.letcode.tree.base.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @program: zyfboot-javabasic
 * @description: 二叉树的中序遍历(简单)
 * @author: zhangyanfeng
 * @create: 2024-08-22 10:45
 **/
public class InorderTraversalSolution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode current = root;

        while (current != null || !stack.isEmpty()) {
            // 先遍历左子树,将节点入栈
            while (current != null) {
                stack.push(current);
                current = current.left;
            }

            // 弹出栈顶元素并访问
            current = stack.pop();
            result.add(current.val);

            // 处理右子树
            current = current.right;
        }

        return result;
    }

    // 测试主函数
    public static void main(String[] args) {
        // 构造测试用例
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);

        // 创建 Solution 实例并进行测试
        InorderTraversalSolution solution = new InorderTraversalSolution();
        List<Integer> result = solution.inorderTraversal(root);

        // 打印结果
        System.out.println(result);  // 输出应为 [1, 3, 2]
    }
}

  具体可见:LeetCode 热题 100 回顾_leetcode热题100-CSDN博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值