力扣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;
    }
}
相关推荐
小安同学iter1 天前
SQL50+Hot100系列(11.7)
java·算法·leetcode·hot100·sql50
_dindong1 天前
笔试强训:Week-4
数据结构·c++·笔记·学习·算法·哈希算法·散列表
星释1 天前
Rust 练习册 :Nucleotide Codons与生物信息学
开发语言·算法·rust
寂静山林1 天前
UVa 1366 Martian Mining
算法
陌路201 天前
S12 简单排序算法--冒泡 选择 直接插入 希尔排序
数据结构·算法·排序算法
雾岛—听风1 天前
P1012 [NOIP 1998 提高组] 拼数
算法
papership1 天前
【入门级-算法-5、数值处理算法:高精度的乘法】
数据结构·算法
earthzhang20211 天前
【1039】判断数正负
开发语言·数据结构·c++·算法·青少年编程
谈笑也风生1 天前
只出现一次的数字 II(一)
数据结构·算法·leetcode
蕓晨1 天前
auto 自动类型推导以及注意事项
开发语言·c++·算法