package lc114_;
import java.util.*;
class TreeNode { TreeNode left, right; int val;
public TreeNode(int val) { this.val = val; } }
public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); String[] input = in.nextLine().split(","); Integer[] output = new Integer[input.length]; for (int i = 0; i < input.length; i++) { if(input[i].equals("null")) { output[i] = null; }else{ output[i] = Integer.parseInt(input[i]); } }
LinkedList<Integer> inputList = new LinkedList<>(Arrays.asList(output)); TreeNode treeNode = buildTree(inputList); System.out.println(preorderTraversal(treeNode)); }
public static TreeNode buildTree(LinkedList<Integer> inputList){ TreeNode node = null; if (inputList ==null || inputList.isEmpty()){ return null; } Integer data = inputList.removeFirst(); if (data != null){ node = new TreeNode(data); node.left = buildTree(inputList); node.right = buildTree(inputList); } return node; }
public static List<Integer> preorderTraversal(TreeNode root) { List<Integer> result = new ArrayList<>(); preorder(root, result); return result; }
public static void preorder(TreeNode root, List<Integer> result) { if (root == null) { return; } result.add(root.val); preorder(root.left, result); preorder(root.right, result); } }
|