力扣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;
    }
}
相关推荐
侠客行031721 小时前
Mybatis连接池实现及池化模式
java·mybatis·源码阅读
蛇皮划水怪21 小时前
深入浅出LangChain4J
java·langchain·llm
老毛肚1 天前
MyBatis体系结构与工作原理 上篇
java·mybatis
那个村的李富贵1 天前
CANN加速下的AIGC“即时翻译”:AI语音克隆与实时变声实战
人工智能·算法·aigc·cann
风流倜傥唐伯虎1 天前
Spring Boot Jar包生产级启停脚本
java·运维·spring boot
power 雀儿1 天前
Scaled Dot-Product Attention 分数计算 C++
算法
Yvonne爱编码1 天前
JAVA数据结构 DAY6-栈和队列
java·开发语言·数据结构·python
Re.不晚1 天前
JAVA进阶之路——无奖问答挑战1
java·开发语言
你这个代码我看不懂1 天前
@ConditionalOnProperty不直接使用松绑定规则
java·开发语言
fuquxiaoguang1 天前
深入浅出:使用MDC构建SpringBoot全链路请求追踪系统
java·spring boot·后端·调用链分析