欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 力扣 LeetCode 94. 二叉树的中序遍历(Day6:二叉树)

力扣 LeetCode 94. 二叉树的中序遍历(Day6:二叉树)

2025/9/16 10:19:51 来源:https://blog.csdn.net/qq_61504864/article/details/143813214  浏览:    关键词:力扣 LeetCode 94. 二叉树的中序遍历(Day6:二叉树)

解题思路:

方法一:递归(左中右)

class Solution {List<Integer> res = new ArrayList<>();public List<Integer> inorderTraversal(TreeNode root) {recur(root);return res;}public void recur(TreeNode root) {if (root == null) return;recur(root.left);res.add(root.val);recur(root.right);}
}

方法二:迭代(非递归法)

前中后序迭代法都是使用栈

前序和后序使用类似的方法

中序方法不同与前序和后序,需要单独区分

 cur != null 时,首先 cur = cur.left 遍历到底进行栈push

为空时,回到上一个不为空的位置并弹出该值,继续 cur = cur.left 遍历该值右边的位置

注意while循环条件

class Solution {public List<Integer> inorderTraversal(TreeNode root) {Deque<TreeNode> stack = new ArrayDeque<>();List<Integer> res = new ArrayList<>();if (root == null) return res;TreeNode cur = root;while (cur != null || !stack.isEmpty()) {if (cur != null) {stack.push(cur);cur = cur.left;} else {cur = stack.pop();res.add(cur.val);cur = cur.right;}}return res;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词