力扣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;
    }
}
相关推荐
大江东去浪淘尽千古风流人物12 分钟前
【VLN】VLN(Vision-and-Language Navigation视觉语言导航)算法本质,范式难点及解决方向(1)
人工智能·python·算法
独好紫罗兰1 小时前
对python的再认识-基于数据结构进行-a003-列表-排序
开发语言·数据结构·python
wuhen_n1 小时前
JavaScript内置数据结构
开发语言·前端·javascript·数据结构
努力学算法的蒟蒻1 小时前
day79(2.7)——leetcode面试经典150
算法·leetcode·职场和发展
2401_841495641 小时前
【LeetCode刷题】二叉树的层序遍历
数据结构·python·算法·leetcode·二叉树··队列
AC赳赳老秦1 小时前
2026国产算力新周期:DeepSeek实战适配英伟达H200,引领大模型训练效率跃升
大数据·前端·人工智能·算法·tidb·memcache·deepseek
独好紫罗兰1 小时前
对python的再认识-基于数据结构进行-a002-列表-列表推导式
开发语言·数据结构·python
2401_841495641 小时前
【LeetCode刷题】二叉树的直径
数据结构·python·算法·leetcode·二叉树··递归
budingxiaomoli1 小时前
优选算法-字符串
算法
我是咸鱼不闲呀2 小时前
力扣Hot100系列19(Java)——[动态规划]总结(上)(爬楼梯,杨辉三角,打家劫舍,完全平方数,零钱兑换)
java·leetcode·动态规划