力扣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;
    }
}
相关推荐
MM_MS8 小时前
Halcon变量控制类型、数据类型转换、字符串格式化、元组操作
开发语言·人工智能·深度学习·算法·目标检测·计算机视觉·视觉检测
独自破碎E9 小时前
【二分法】寻找峰值
算法
mit6.8249 小时前
位运算|拆分贪心
算法
ghie909010 小时前
基于MATLAB的TLBO算法优化实现与改进
开发语言·算法·matlab
恋爱绝缘体110 小时前
2020重学C++重构你的C++知识体系
java·开发语言·c++·算法·junit
wuk99810 小时前
VSC优化算法MATLAB实现
开发语言·算法·matlab
Z1Jxxx10 小时前
加密算法加密算法
开发语言·c++·算法
乌萨奇也要立志学C++10 小时前
【洛谷】递归初阶 三道经典递归算法题(汉诺塔 / 占卜 DIY/FBI 树)详解
数据结构·c++·算法
vyuvyucd11 小时前
C++引用:高效编程的别名利器
算法
鱼跃鹰飞11 小时前
Leetcode1891:割绳子
数据结构·算法