You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在IDE中创建并加载二叉树,完成LeetCode二叉树前序遍历类问题

How to Test Your Binary Tree Preorder Traversal Code in an IDE

Hey there! I totally get where you're coming from—LeetCode takes care of all the messy setup like creating the binary tree and feeding it to your Solution class, so it's easy to feel stuck when trying to replicate that in your own IDE. Let's fix that by building a complete, testable version of your code.

First, let's clean up a few small issues in your original code:

  • The import for List was pointing to an internal XML schema class, which is wrong—we need the standard java.util.List instead.
  • I'll also finish the preorderTraversal method (both iterative and recursive versions, since you had a Stack in your code) so you can see how it all comes together.

Here's the full, runnable code you can drop into your IDE:

package cs_gator_problem_classification;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class PreorderTraversal_Problem1 {
    // Definition for a binary tree node.
    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(int x) { val = x; }
    }

    static class Solution {
        // Iterative approach (using Stack, matching your initial code)
        public List<Integer> preorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            if (root == null) return result;

            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);

            while (!stack.isEmpty()) {
                TreeNode current = stack.pop();
                result.add(current.val);

                // Push right first so left is processed next (Stack is LIFO)
                if (current.right != null) {
                    stack.push(current.right);
                }
                if (current.left != null) {
                    stack.push(current.left);
                }
            }
            return result;
        }

        // Optional: Recursive approach for comparison
        public List<Integer> preorderTraversalRecursive(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            traverse(root, result);
            return result;
        }

        private void traverse(TreeNode node, List<Integer> result) {
            if (node == null) return;
            result.add(node.val);
            traverse(node.left, result);
            traverse(node.right, result);
        }
    }

    // Main method to test your code
    public static void main(String[] args) {
        // Step 1: Build a sample binary tree
        // Let's create this tree:
        //     1
        //      \
        //       2
        //      /
        //     3
        TreeNode root = new TreeNode(1);
        root.right = new TreeNode(2);
        root.right.left = new TreeNode(3);

        // Step 2: Initialize Solution and run traversal
        Solution solution = new Solution();
        List<Integer> iterativeResult = solution.preorderTraversal(root);
        List<Integer> recursiveResult = solution.preorderTraversalRecursive(root);

        // Step 3: Print the results to verify
        System.out.println("Iterative Preorder Traversal Result: " + iterativeResult); // Should output [1,2,3]
        System.out.println("Recursive Preorder Traversal Result: " + recursiveResult); // Should output [1,2,3]
    }
}

Key Things to Note:

  • Building the Binary Tree: In the main method, we manually construct each TreeNode and link them together using the left and right properties. You can adjust this to create any test tree you want (empty tree, single node, full binary tree, etc.).
  • Testing the Solution: We create an instance of the Solution class, call the traversal methods, and print the results to check if they match the expected preorder sequence (root -> left -> right).
  • Import Fix: We replaced the incorrect com.sun.xml.internal.bind.v2.schemagen.xmlschema.List import with java.util.List and java.util.ArrayList—these are the standard collections you should use.

Just run the main method in your IDE, and you'll immediately see if your code works as expected, plus catch any syntax errors in real-time.

内容的提问来源于stack exchange,提问作者tom44

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:19:36