力扣hot100 - 94、二叉树的中序遍历

题目:

法一:递归

法二:迭代

整体思路:首先不断向左遍历左孩子,同时将遍历的节点存入栈中,如果当前节点为空,那么此时栈顶的元素就是中序遍历的第一个元素,将该元素弹出并且存入结果集合中,然后遍历该节点的右孩子,如果为空直接从栈里弹出一个节点,并存入结果集合中,不为空则不断向左遍历左孩子。定义一个结果reslut集合存储元素,一个栈存储节点。

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> result = new ArrayList();
        Deque<TreeNode> stack = new ArrayDeque();
        if( root == null) return result;
        TreeNode cur = root;
        while(!stack.isEmpty() || cur != null){
            if(cur != null){
                stack.push(cur);
                cur = cur.left;
            }else{
                cur = stack.peek();
                stack.pop();
                result.add(cur.val);
                cur = cur.right;
            }
            

        }

         return result;
    }

}
相关推荐
踩坑记录10 分钟前
leetcode hot100 35. 搜索插入位置 medium 二分查找
leetcode
散峰而望2 小时前
C++ 启程:从历史到实战,揭开命名空间的神秘面纱
c语言·开发语言·数据结构·c++·算法·github·visual studio
Ethan Hunt丶2 小时前
MSVTNet: 基于多尺度视觉Transformer的运动想象EEG分类模型
人工智能·深度学习·算法·transformer·脑机接口
仟濹2 小时前
【算法打卡day10(2026-02-24 周二)复习算法:DFS BFS 并查集】
算法·深度优先·图论·dfs·bfs·广度优先·宽度优先
-海绵东东-2 小时前
哈希表······················
算法·leetcode·散列表
Darkwanderor3 小时前
数据结构 - 并查集的应用
数据结构·c++·并查集
LuDvei3 小时前
LINUX文件操作函数
java·linux·算法
XW01059993 小时前
4-11判断素数
前端·python·算法·素数
浅念-4 小时前
C++ 继承
开发语言·c++·经验分享·笔记·学习·算法·继承
算法备案代理4 小时前
深度合成算法备案:生成式AI需要备案吗?
人工智能·算法·算法备案