94. 二叉树的中序遍历

发布于 19 天前  16 次阅读


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

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

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

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

中序遍历:

左、根、右

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public static List<Integer> inorderTraversal(TreeNode root) {
        LinkedList<Integer> list = new LinkedList<>();
        inorder(root, list);
        return list;
    }

    public static void inorder(TreeNode root, LinkedList<Integer> list) {
        if (root==null) {
            return;
        }
        inorder(root.left, list);
        list.add(root.val);
        inorder(root.right, list);
    }
}

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户

内存消耗:39.5 MB, 在所有 Java 提交中击败了74.54%的用户