力扣94.二叉树的中序遍历(递归and迭代法)(java)

题目来源

94. 二叉树的中序遍历 - 力扣(LeetCode)

递归法

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<>();
        inorder(root,res);
        return res;
    }

    private void inorder(TreeNode root, List<Integer> res) {
        if(root == null) return ;
        // 左中右,这样子记录
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }
}

迭代法

代码分析

递归啥的不赘述了。迭代法就是模拟递归栈。

因为如果想要实现左中右的遍历效果(也就是中序遍历效果),就需要先找到最左边的,

但是找到最左边怎么回去呢?如果我在沿途找的时候,把过程中的结点存放起来,而栈最合适。

遍历结果就存放在动态数组中,(ArrayList)

代码

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<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curr = root;

        while(curr != null || !stack.isEmpty()) {
            //递归找最左边,入栈
            while(curr != null) {
                stack.push(curr);
                curr = curr.left;
            }
            // 回退, 出栈
            curr = stack.pop();
            res.add(curr.val);
            //遍历右边
            curr = curr.right;
        }
        return res;
    }
}
相关推荐
豆沙沙包?10 分钟前
2025年--Lc298-1019. 链表中的下一个更大节点(栈)--java版
java·数据结构·链表
fengfuyao98511 分钟前
匈牙利算法的MATLAB实现
java·算法·matlab
路过君_P14 分钟前
C++ 算法题解:迷宫寻路
c++·算法·深度优先
罗湖老棍子23 分钟前
二维vector完全指南1:从定义到增删改查
数据结构·c++·算法·stl
再卷也是菜23 分钟前
C++篇(22)LRU Cache
数据结构·c++·算法
语落心生25 分钟前
海量数据集的AI自动化预测打标 -- 振动特征多标签分类
算法
语落心生29 分钟前
海量数据集AI自动化打标 - 温度周期检测
算法
语落心生38 分钟前
海量数据集的AI自动化预测打标 -- 矿业音频分类
算法
吃着火锅x唱着歌41 分钟前
LeetCode 3185.构成整天的下标对数目II
算法·leetcode·职场和发展
程序猿多布1 小时前
数据结构 之 栈和队列
数据结构··队列