我已经在Leetcode上完成了以下问题:https://leetcode.com/problems/binary-tree-preorder-traversal/description/,但希望能够在我的IDE中编写类似的问题,这样我就可以立即看到语法错误。问题是Leetcode为您提供了二叉树,您只需编写类Solution
,因此我不确定如何创建二进制树并将其加载到Solution
。
package cs_gator_problem_classification;
import java.util.ArrayList;
import java.util.Stack;
import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;
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 {
public ArrayList<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> s = new Stack<TreeNode>();
ArrayList<Integer> result = new ArrayList<Integer>();
s.push(root);
while(!s.empty()) {
TreeNode current = s.peek();
s.pop();
if(current != null) {
s.push(current.right);
s.push(current.left);
result.add(current.val);
}
}
//result.add(1);
System.out.println("result: " + result);
return result;
}
}
public static void main(String[] args) {
System.out.println("test");
TreeNode originalRoot = new TreeNode(3);
Solution solution = new Solution();
}
}
答案 0 :(得分:0)
so I'm not sure how to create and load the binary tree into Solution
以下是两种简单的方法,您可以为给定的根对象创建二叉树。您可以通过设置新的左\右节点来制作您喜欢的任何类型的数据。
public static void makeTreeData(TreeNode root) {
if (null == root) {
throw new IllegalArgumentException("root should not be null.");
}
if (root.val > 10) {
return;
}
TreeNode left = new TreeNode(root.val * 2);
makeTreeData(left);
TreeNode right = new TreeNode(root.val * 2 + 1);
makeTreeData(right);
root.left = left;
root.right = right;
}
public static void makeTreeData2(TreeNode root) {
root.right = new TreeNode(2);
root.right.left = new TreeNode(3);
}
只需使用刚创建的TreeNode调用solution.preorderTraversal(TreeNode)
方法即可。你可以在控制台中看到结果。
public static void main(String[] args) {
System.out.println("test");
TreeNode originalRoot = new TreeNode(3);
Solution solution = new Solution();
System.Out.println(solution.preorderTraversal(originalRoot));
}