【二叉树】Leetcode 94. 二叉树的中序遍历【简单】-Java实现中序遍历

public class InorderTraversal {
  
   static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        inorderTraversalHelper(root, result);
        return result;
    }

    private void inorderTraversalHelper(TreeNode node, List<Integer> result) {
        if (node == null) {
            return;
        }

        inorderTraversalHelper(node.left, result);
        result.add(node.val);
        inorderTraversalHelper(node.right, result);
    }

    public static void main(String[] args) {
        // 示例用法
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(4);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);

        InorderTraversal solution = new InorderTraversal();
        List<Integer> result = solution.inorderTraversal(root);

        System.out.println(result);  // 输出:[4, 1, 3, 2]
    }
}

上一篇:使用GO语言验证证书的有效期


下一篇:Java基础【泛型】-泛型使用注意事项