题目来源: 94. 二叉树的中序遍历
题目描述:
- 描述: 给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
- 难度:
- 示例:
示例1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例2:
输入:root = []
输出:[]
具体实现:迭代
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<Integer>();
Deque<TreeNode> stk = new LinkedList<TreeNode>();
while (root != null || !stk.isEmpty()) {
while (root != null) {
stk.push(root);
root = root.left;
}
root = stk.pop();
res.add(root.val);
root = root.right;
}
return res;
}
}
复杂度分析:
- 时间复杂度:O(n),其中n 是数组的长度。
- 空间复杂度:O(n)。