94. 二叉树的中序遍历
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
示例 1:

输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
示例 4:

输入:root = [1,2]
输出:[2,1]
示例 5:

输入:root = [1,null,2]
输出:[1,2]
提示:
- 树中节点数目在范围
[0, 100]内 -100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
思路:
树的遍历方式主要有两种,递归和迭代。递归比较简洁且便于理解,前中后序遍历都可以用递归。但本题要求不要用递归,那自然就是需要迭代了,思路其实就是广度优先遍历,根据不同情况选择队列或者栈做辅助容器即可。如层序遍历需要先进先出,所以选择队列做辅助容器,而中序遍历需要先进后出,故我们选择栈作为辅助容器。
Java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
// //方法一:递归
// List<Integer> res = new ArrayList<>();
// if(root == null) return res;
// infixOrder(root,res);
// return res;
// }
// private void infixOrder(TreeNode node,List<Integer> res){
// if(node.left != null){
// infixOrder(node.left,res);
// }
// res.add(node.val);
// if(node.right != null){
// infixOrder(node.right,res);
// }
//方法二:迭代,使用深度优先遍历,用栈作为辅助容器
List<Integer> res = new ArrayList<>();
if(root == null) return res;
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = root;
while(cur != null || !stack.isEmpty()){
while(cur != null){//将当前结点左孩子都入栈
stack.push(cur);
cur = cur.left;
}//左边到头,开始遍历右子树
cur = stack.pop();
res.add(cur.val);
cur = cur.right;//当前结点的右子树
}
return res;
}
}

296

被折叠的 条评论
为什么被折叠?



