Exemple #1
0
 public static TreeNode createTree(ArrayList<String> list) {
   LinkedList<NodeWithBranch> queue = new LinkedList<>();
   TreeNode head = new TreeNode(0);
   queue.addLast(new NodeWithBranch(head, 0));
   for (String s : list) {
     NodeWithBranch node = queue.removeFirst();
     if (!s.equals(NULL)) {
       if (node.branch == 0) {
         node.tree.left = new TreeNode(Integer.parseInt(s));
         queue.addLast(new NodeWithBranch(node.tree.left, 0));
         queue.addLast(new NodeWithBranch(node.tree.left, 1));
       } else {
         node.tree.right = new TreeNode(Integer.parseInt(s));
         queue.addLast(new NodeWithBranch(node.tree.right, 0));
         queue.addLast(new NodeWithBranch(node.tree.right, 1));
       }
     }
   }
   return head.left;
 }
Exemple #2
0
 public static ArrayList<String> serializeTree(TreeNode tree) {
   ArrayList<String> res = new ArrayList<>();
   LinkedList<TreeNode> queue = new LinkedList<>();
   queue.addLast(tree);
   while (!queue.isEmpty()) {
     TreeNode node = queue.removeFirst();
     if (node == null) {
       res.add(NULL);
     } else {
       res.add(String.valueOf(node.val));
       queue.add(node.left);
       queue.add(node.right);
     }
   }
   while (res.size() > 1 && res.get(res.size() - 1).equals(NULL)) {
     res.remove(res.size() - 1);
   }
   return res;
 }