day77 94. 二叉树的中序遍历(C++)

61 阅读1分钟

题目来源: 94. 二叉树的中序遍历

题目描述:

  • 描述: 给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
  • 难度: 简单\color{5AB726}{简单}
  • 示例: inorder_1.jpg
示例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)。