力扣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;
    }
}
相关推荐
Ulyanov15 小时前
用声明式语法重新定义Python桌面UI:QML+PySide6现代开发入门(一)
开发语言·python·算法·ui·系统仿真·雷达电子对抗仿真
数据科学小丫15 小时前
特征工程处理
人工智能·算法·机器学习
z落落16 小时前
C#参数区别
java·算法·c#
c2385617 小时前
vector(下)
数据结构·算法
z落落17 小时前
C# 冒泡排序+选择排序 + Array.Sort 自定义排序
数据结构·算法
wyy1851007372817 小时前
双路并行:一套匹配算法如何解决中文制单的两大核心难题
算法·ai·crm·crm系统
s_w.h17 小时前
【 linux 】文件系统
linux·运维·服务器·算法·bash
无限进步_17 小时前
【C++】weak_ptr、循环引用与线程安全
开发语言·数据结构·c++·算法·安全
罗超驿17 小时前
9.LeetCode 209. 长度最小的子数组 | 滑动窗口专题详解
java·算法·leetcode·面试
水蓝烟雨17 小时前
0135. 分发糖果
算法·leetcode