力扣94题(java语言)
创始人
2024-11-11 09:42:27

题目 

思路

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

遍历顺序步骤:

  1. 遍历左子树
  2. 访问根节点
  3. 遍历右子树
package algorithm_leetcode;  import java.util.ArrayList; import java.util.List; import java.util.Stack;  public class Solution_94 { 	public List inorderTraversal(TreeNode root) { 		// 待处理节点 		Stack stack = new Stack<>(); 		// 结果 		List 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;     } }

相关内容

热门资讯

裸辞做“一人公司”,我后悔了 去年这个时候,一位以色列程序员正在东南亚旅行。他顺手把一个在脑子里转了很久的想法做成了产品,一个让任...
南京建成国内首个Pre-6G试... 4月21日,2026全球6G技术与产业生态大会在南京开幕。全息互动技术展台前,一名远在北京的工作人员...
超梵求职受邀参加“2025抖音... 超梵求职受邀参加“2025抖音巨量引擎成人教育行业生态大会”,探讨分享优质内容传播,服务万千学员。 ...
摩托罗拉Razr 2026(R... IT之家 4 月 22 日消息,摩托罗拉宣布新一代 Razr 折叠手机将于 4 月 29 日在美国发...
库克卸任,特纳斯领航:苹果新纪... 苹果首席执行官蒂姆·库克将卸任,硬件工程主管约翰·特纳斯将接任,苹果公司今天宣布此事。 库克将在夏季...