力扣94题(java语言)

题目

思路

使用一个栈来模拟递归的过程,以非递归的方式完成中序遍历(使用栈可以避免递归调用的空间消耗)。

遍历顺序步骤:

  1. 遍历左子树
  2. 访问根节点
  3. 遍历右子树
java 复制代码
package algorithm_leetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Solution_94 {
	public List<Integer> inorderTraversal(TreeNode root) {
		// 待处理节点
		Stack<TreeNode> stack = new Stack<>();
		// 结果
		List<Integer> output_arr = new ArrayList<>();
		
		// 如果root为空
		if (root == null) {
			// 返回空的 output_arr
			return output_arr;
		}
		
		// 初始化为根节点
		TreeNode current = root;
		
		// 循环 只要当前节点不为空,并且栈不为空 
		while (current != null || !stack.isEmpty()) {
			// 当前节点不为空,直到左子树为空
			while (current != null) {
				// 添加到栈
				stack.push(current);
				// 当前节点移动到左子节点
				current = current.left;
			}
			// 弹出栈节点
			current = stack.pop();
			// 添加到结果中
			output_arr.add(current.val);
			// 如果有右子节点,就移动到右子节点
			current = current.right;
		}
		
		return output_arr;
		
	}
}

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;
    }
}
相关推荐
invicinble4 分钟前
对于线程产生理解
java
程序员二叉5 分钟前
【Java】String 全套高频面试题详解
java·开发语言·面试
仍然.6 分钟前
算法题目---BFS解决FloodFill算法问题
算法·宽度优先
字节高级特工11 分钟前
C++11(三)终极指南:可变参数模板与包装器详解
java·开发语言·c++·后端
Sirius Wu16 分钟前
MoE与Fengyu-Dense_架构对比及训练方案
人工智能·深度学习·算法·机器学习·语言模型·架构
却道天凉_好个秋17 分钟前
HEVC(一):环路滤波
人工智能·算法·计算机视觉·环路滤波
8Qi824 分钟前
LeetCode 300 & 674:最长递增子序列 vs 最长连续递增子序列
算法·leetcode·职场和发展·动态规划
用户2986985301429 分钟前
Java 实现 Word 文档内容复制:段落、章节与全文合并技巧
java·后端
sheeta199833 分钟前
LeetCode 补拙笔记 日期:2026.06.07 题目:283. 移动零
笔记·算法·leetcode
摇滚侠33 分钟前
Maven 入门+高深 SSM 案例 111-112
java·数据库·maven