算法:94. 二叉树的中序遍历

给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。

示例 1:

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

示例 2:

输入:root = []
输出:[]

示例 3:

输入:root = [1]
输出:[1]

提示:

  • 树中节点数目在范围 [0, 100] 内
  • -100 <= Node.val <= 100
方法一:递归
class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        inorder(root, res);
        return res;
    }

    public void inorder(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        inorder(root.left, res);
        res.add(root.val);
        inorder(root.right, res);
    }
}
方法二:迭代
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;
    }
}

相关推荐

  1. [94] js

    2024-06-08 12:24:02       29 阅读
  2. LeetCode 94.

    2024-06-08 12:24:02       12 阅读
  3. LeetCode-94-

    2024-06-08 12:24:02       11 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-08 12:24:02       17 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-08 12:24:02       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-08 12:24:02       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-08 12:24:02       18 阅读

热门阅读

  1. Vue Router——hash模式和 history模式

    2024-06-08 12:24:02       10 阅读
  2. Elasticsearch 认证模拟题 - 10

    2024-06-08 12:24:02       10 阅读
  3. TCP和udp能使用同一个端口通讯吗

    2024-06-08 12:24:02       8 阅读
  4. 设计模式总结

    2024-06-08 12:24:02       6 阅读
  5. UVa1116/LA2429 Puzzle

    2024-06-08 12:24:02       5 阅读
  6. #07 使用Stable Diffusion生成高质量图片的技巧

    2024-06-08 12:24:02       8 阅读
  7. HTTP参数污染漏洞

    2024-06-08 12:24:02       8 阅读