Coding problems on trees are asked frequently at tech interviews. Creating a mirror tree from the given binary tree is one such popular DSA problem. Let's look at what the problem entails and how to solve it.
Given the root of a binary tree, transform the tree in-place into its mirror image.
0
/ \
1 2
/ \ / \
3 4 5 6
Output:
0
/ \
2 1
/ \ / \
6 5 4 3
Constraints:
We provided two solutions: a recursive one and an iterative one.
We will refer to the total number of nodes in the given tree as n
.
This is a recursive solution. The main task is to swap left and right children for every node of the tree. We are calling the function recursively and making sure that leaf nodes are handled first then their parents and it goes up to the root node.
O(n).
O(n).
That extra space is used for the call stack.
O(n).
Input is O(n) because we are storing n
nodes relationships and each relationship occupies O(1) space and auxiliary space used is O(n). So, O(n) + O(n) = O(n).
/*
* Asymptotic complexity in terms of number of nodes \`n\` in the given tree:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/
public static void mirror_image(BinaryTreeNode root) {
root = mirror_image_util(root);
}
public static BinaryTreeNode mirror_image_util(BinaryTreeNode root){
if (root == null)
return root;
BinaryTreeNode left = mirror_image_util(root.left);
BinaryTreeNode right = mirror_image_util(root.right);
// Swap the left and right pointers.
root.left = right;
root.right = left;
return root;
}
This solution traverses the tree breadth first using a loop and a queue, without making use of recursion. We initialize the queue with the root node. Then we do the following until the queue is empty:
O(n).
O(n).
We are using a queue for storing nodes to do BFS traversal over the tree. In the worst case scenario, queue size will be n
.
O(n).
Input is O(n) because we are storing n
nodes relationships and each relationship occupies O(1) space and auxiliary space used is O(n). So, O(n) + O(n) = O(n).
/*
* Asymptotic complexity in terms of number of nodes \`n\` in the given tree:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/
public static void mirror_image(BinaryTreeNode root) {
if (root == null)
return;
Queue<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>();
queue.add(root);
// Do BFS. While doing BFS, keep swapping
// left and right children
while(!queue.isEmpty()) {
// Pop top node from queue.
BinaryTreeNode cur_node = queue.poll();
// Swap left child with right child.
BinaryTreeNode temp = cur_node.left;
cur_node.left = cur_node.right;
cur_node.right = temp;
// Push left and right children.
if (cur_node.left != null)
queue.add(cur_node.left);
if (cur_node.right != null)
queue.add(cur_node.right);
}
}
We hope that these solutions to creating a mirror image of a binary tree have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.
If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.
Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.
We offer 17 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:
To learn more, register for the FREE webinar.
package main
import (
"bufio"
"bytes"
"container/heap"
"container/list"
"container/ring"
"fmt"
"io"
"math"
"math/rand"
"os"
"encoding/json"
"strconv"
"strings"
"sort"
"unicode"
)
var _ = bufio.ScanBytes
var _ = bytes.Count
var _ = heap.Init
var _ = list.New
var _ = ring.New
var _ = io.EOF
var _ = math.Pow
var _ = rand.Int
var _ = strconv.Atoi
var _ = strings.TrimRight
var _ = sort.Slice
var _ = unicode.IsDigit
type BinaryTreeNode struct {
value int
left *BinaryTreeNode
right *BinaryTreeNode
}
func output_int32(argument int) {
output_write(strconv.Itoa(argument))
}
func output_BinaryTreeNode_int32(argument *BinaryTreeNode) {
current_level_nodes := []*BinaryTreeNode{argument}
current_level_nodes_start := 0
nodes_to_print := make([]*BinaryTreeNode, 0)
print_newlines_before_node_indices := make([]int, 0)
print_newlines_before_node_indices_start := 0
for len(current_level_nodes) - current_level_nodes_start > 0 {
next_level_nodes := make([]*BinaryTreeNode, 0)
for len(current_level_nodes) - current_level_nodes_start > 0 {
node := current_level_nodes[current_level_nodes_start]
current_level_nodes_start += 1
nodes_to_print = append(nodes_to_print, node)
if (node != nil) {
next_level_nodes = append(next_level_nodes, node.left, node.right)
}
}
current_level_nodes = next_level_nodes
current_level_nodes_start = 0
print_newlines_before_node_indices = append(print_newlines_before_node_indices, len(nodes_to_print))
}
for len(nodes_to_print) > 1 && nodes_to_print[len(nodes_to_print) - 1] == nil {
nodes_to_print = nodes_to_print[:len(nodes_to_print) - 1]
}
output_write("[")
if (nodes_to_print[0] == nil) {
output_write("null")
} else {
output_int32(nodes_to_print[0].value)
}
for i := 1; i < len(nodes_to_print); i++ {
if i == print_newlines_before_node_indices[print_newlines_before_node_indices_start] {
output_write(",\n")
print_newlines_before_node_indices_start += 1
} else {
output_write(", ")
}
if (nodes_to_print[i] == nil) {
output_write("null")
} else {
output_int32(nodes_to_print[i].value)
}
}
output_write("]")
}
func input_int32(data interface{}) int {
argument:= int(data.(float64))
return argument
}
func input_BinaryTreeNode_int32(data interface{}) *BinaryTreeNode {
json_array:= data.([]interface{})
json_array_length:= len(json_array)
var argument *BinaryTreeNode // Root of the tree that we return.
nodes_with_uninitialized_children := make([]*BinaryTreeNode, 0)
next_child_is_left := true
for i:= 0; i < int(json_array_length); i++ {
var new_node *BinaryTreeNode
if json_array[i] != nil {
new_node = &BinaryTreeNode {value: input_int32(json_array[i]), left: nil, right: nil,}
if argument == nil {
argument = new_node
}
}
if len(nodes_with_uninitialized_children) > 0 {
parent_node := nodes_with_uninitialized_children[0]
nodes_with_uninitialized_children = nodes_with_uninitialized_children[1:]
if next_child_is_left {
parent_node.left = new_node
} else {
parent_node.right = new_node
}
next_child_is_left = !next_child_is_left
}
if new_node != nil {
nodes_with_uninitialized_children = append(nodes_with_uninitialized_children, new_node, new_node)
}
}
return argument
}
func output_write(x string) {
output_string.WriteString(x)
}
var output_string strings.Builder
func main() {
var root *BinaryTreeNode
var data map[string]interface{}
dec:= json.NewDecoder(os.Stdin)
dec.Decode(&data)
root = input_BinaryTreeNode_int32(data["root"])
var original_out = os.Stdout
os.Stdout = os.Stderr
mirror_image(root)
result:= root
os.Stdout = original_out
if result != nil {
remaining_nodes := []*BinaryTreeNode{result}
number_of_nodes := 0
for len(remaining_nodes) > 0 {
number_of_nodes++
if number_of_nodes > 2000000 {
break
}
node := remaining_nodes[len(remaining_nodes) - 1]
remaining_nodes = remaining_nodes[:len(remaining_nodes) - 1]
if (node.left != nil) {
remaining_nodes = append(remaining_nodes, node.left)
}
if node.right != nil {
remaining_nodes = append(remaining_nodes, node.right)
}
}
if number_of_nodes > 2000000 {
fmt.Fprintf(os.Stderr, "-------- You returned a tree with either a cycle or too many nodes --------\n")
os.Exit(9)
}
}
output_BinaryTreeNode_int32(result)
output_write("\n")
fmt.Print(output_string.String())
}
/*
For your reference:
type BinaryTreeNode struct {
value int
left *BinaryTreeNode
right *BinaryTreeNode
}
*/
func mirror_image(root *BinaryTreeNode) {
// Write your code here.
}
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import org.json.*;
class BinaryTreeNode {
Integer value;
BinaryTreeNode left;
BinaryTreeNode right;
BinaryTreeNode(Integer value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class Solution {
}
class Result {
static void output_int32(Integer argument) {
output_string.append(argument);
}
static void output_BinaryTreeNode_int32(BinaryTreeNode argument) {
Deque<BinaryTreeNode> current_level_nodes = new LinkedList<>();
current_level_nodes.addLast(argument);
ArrayList<BinaryTreeNode> nodes_to_print = new ArrayList<>();
Deque<Integer> print_newlines_before_node_indices = new LinkedList<>();
while (!current_level_nodes.isEmpty()) {
Deque<BinaryTreeNode> next_level_nodes = new LinkedList<>();
while (!current_level_nodes.isEmpty()) {
BinaryTreeNode node = current_level_nodes.removeFirst();
nodes_to_print.add(node);
if (node != null) {
next_level_nodes.add(node.left);
next_level_nodes.add(node.right);
}
}
current_level_nodes = next_level_nodes;
print_newlines_before_node_indices.add(nodes_to_print.size());
}
while (nodes_to_print.size() > 1 && nodes_to_print.get(nodes_to_print.size() - 1) == null) {
nodes_to_print.remove(nodes_to_print.size() - 1);
}
output_string.append('[');
if (nodes_to_print.get(0) == null) {
output_string.append("null");
} else {
output_int32(nodes_to_print.get(0).value);
}
for (int i = 1; i < nodes_to_print.size(); i++) {
if (i == print_newlines_before_node_indices.getFirst()) {
output_string.append(",\n");
print_newlines_before_node_indices.removeFirst();
} else {
output_string.append(", ");
}
if (nodes_to_print.get(i) == null) {
output_string.append("null");
} else {
output_int32(nodes_to_print.get(i).value);
}
}
output_string.append(']');
}
static Integer input_int32(Object data) {
Integer argument = (Integer) data;
return argument;
}
static BinaryTreeNode input_BinaryTreeNode_int32(Object data) {
JSONArray json_array = (JSONArray) data;
BinaryTreeNode argument = null; // Root of the tree that we return.
Deque<BinaryTreeNode> nodes_with_uninitialized_children = new LinkedList<>();
boolean next_child_is_left = true;
for (Object json_array_item: json_array) {
BinaryTreeNode new_node = null;
if (!JSONObject.NULL.equals(json_array_item)) {
new_node = new BinaryTreeNode(input_int32(json_array_item));
if (argument == null) {
argument = new_node;
}
}
if (!nodes_with_uninitialized_children.isEmpty()) {
BinaryTreeNode parent_node = nodes_with_uninitialized_children.removeFirst();
if (next_child_is_left) {
parent_node.left = new_node;
} else {
parent_node.right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node != null) {
nodes_with_uninitialized_children.addLast(new_node);
nodes_with_uninitialized_children.addLast(new_node);
}
}
return argument;
}
private static final DecimalFormat float_formatter = new DecimalFormat("0.00");
private static final StringBuilder output_string = new StringBuilder();
public static void main(String[] args) throws Exception {
BinaryTreeNode root;
try {
ByteArrayOutputStream json_string = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int length; (length = System.in.read(buffer)) != -1; ) {
json_string.write(buffer, 0, length);
}
JSONObject data = new JSONObject(json_string.toString("UTF-8"));
root = input_BinaryTreeNode_int32(data.get("root"));
} catch (Exception ex) {
System.err.println("reading-input-failed-json");
ex.printStackTrace();
throw ex;
}
PrintStream original_out = System.out;
System.setOut(System.err);
Solution.mirror_image(root);
BinaryTreeNode result = root;
System.setOut(original_out);
if (result != null) {
ArrayList<BinaryTreeNode> remaining_nodes = new ArrayList<>();
remaining_nodes.add(result);
int number_of_nodes = 0;
while (!remaining_nodes.isEmpty()) {
number_of_nodes++;
if (number_of_nodes > 2000000) {
break;
}
BinaryTreeNode node = remaining_nodes.get(remaining_nodes.size() - 1);
remaining_nodes.remove(remaining_nodes.size() - 1);
if (node.left != null) {
remaining_nodes.add(node.left);
}
if (node.right != null) {
remaining_nodes.add(node.right);
}
}
if (number_of_nodes > 2000000) {
throw new RuntimeException("-------- You returned a tree with either a cycle or too many nodes --------");
}
}
output_BinaryTreeNode_int32(result);
output_string.append('\n');
System.out.print(output_string.toString());
}
}
/*
For your reference:
class BinaryTreeNode {
Integer value;
BinaryTreeNode left;
BinaryTreeNode right;
BinaryTreeNode(Integer value) {
this.value = value;
this.left = null;
this.right = null;
}
}
*/
static void mirror_image(BinaryTreeNode root) {
// Write your code here.
}
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Json;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class BinaryTreeNode {
public int value;
public BinaryTreeNode left;
public BinaryTreeNode right;
public BinaryTreeNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class Solution {
}
class Result {
public static void output_int32(int argument) {
textWriter.Write(argument);
}
public static void output_BinaryTreeNode_int32(BinaryTreeNode argument) {
Queue<BinaryTreeNode> current_level_nodes = new Queue<BinaryTreeNode>();
current_level_nodes.Enqueue(argument);
List<BinaryTreeNode> nodes_to_print = new List<BinaryTreeNode>();
Queue<int> print_newlines_before_node_indices = new Queue<int>();
while (current_level_nodes.Count > 0) {
Queue<BinaryTreeNode> next_level_nodes = new Queue<BinaryTreeNode>();
while (current_level_nodes.Count > 0) {
BinaryTreeNode node = current_level_nodes.Dequeue();
nodes_to_print.Add(node);
if (node != null) {
next_level_nodes.Enqueue(node.left);
next_level_nodes.Enqueue(node.right);
}
}
current_level_nodes = next_level_nodes;
print_newlines_before_node_indices.Enqueue(nodes_to_print.Count);
}
while (nodes_to_print.Count > 1 && nodes_to_print[nodes_to_print.Count - 1] == null) {
nodes_to_print.RemoveAt(nodes_to_print.Count - 1);
}
textWriter.Write("[");
if (nodes_to_print[0] == null) {
textWriter.Write("null");
} else {
output_int32(nodes_to_print[0].value);
}
for (int i = 1; i < nodes_to_print.Count; i++) {
if (i == print_newlines_before_node_indices.Peek()) {
textWriter.Write(",\n");
print_newlines_before_node_indices.Dequeue();
} else {
textWriter.Write(", ");
}
if (nodes_to_print[i] == null) {
textWriter.Write("null");
} else {
output_int32(nodes_to_print[i].value);
}
}
textWriter.Write("]");
}
public static int input_int32(Object data) {
int argument = (int) (JsonValue) data;
return argument;
}
public static BinaryTreeNode input_BinaryTreeNode_int32(Object data) {
JsonArray json_array = (JsonArray) data;
BinaryTreeNode argument = null; // Root of the tree that we return.
Queue<BinaryTreeNode> nodes_with_uninitialized_children = new Queue<BinaryTreeNode>();
bool next_child_is_left = true;
foreach (Object json_array_item in json_array) {
BinaryTreeNode new_node = null;
if (json_array_item != null) {
new_node = new BinaryTreeNode(input_int32(json_array_item));
if (argument == null) {
argument = new_node;
}
}
if (nodes_with_uninitialized_children.Count > 0) {
BinaryTreeNode parent_node = nodes_with_uninitialized_children.Dequeue();
if (next_child_is_left) {
parent_node.left = new_node;
} else {
parent_node.right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node != null) {
nodes_with_uninitialized_children.Enqueue(new_node);
nodes_with_uninitialized_children.Enqueue(new_node);
}
}
return argument;
}
public static TextWriter textWriter;
public static void Main(string[] args) {
textWriter = new StreamWriter(Console.OpenStandardOutput());
BinaryTreeNode root;
try {
JsonValue data = JsonValue.Load(new StreamReader(Console.OpenStandardInput()));
root = input_BinaryTreeNode_int32(data["root"]);
} catch (Exception ex) {
Console.Error.WriteLine("reading-input-failed-json");
Console.Error.WriteLine(ex.StackTrace);
throw ex;
}
TextWriter original_out = Console.Out;
Console.SetOut(Console.Error);
Solution.mirror_image(root);
BinaryTreeNode result = root;
Console.SetOut(original_out);
if (result != null) {
List<BinaryTreeNode> remaining_nodes = new List<BinaryTreeNode>();
remaining_nodes.Add(result);
int number_of_nodes = 0;
while (remaining_nodes.Count > 0) {
number_of_nodes++;
if (number_of_nodes > 2000000) {
break;
}
BinaryTreeNode node = remaining_nodes[remaining_nodes.Count - 1];
remaining_nodes.RemoveAt(remaining_nodes.Count - 1);
if (node.left != null) {
remaining_nodes.Add(node.left);
}
if (node.right != null) {
remaining_nodes.Add(node.right);
}
}
if (number_of_nodes > 2000000) {
throw new SystemException("-------- You returned a tree with either a cycle or too many nodes --------");
}
}
output_BinaryTreeNode_int32(result);
textWriter.Write('\n');
textWriter.Flush();
textWriter.Close();
}
}
/*
For your reference:
class BinaryTreeNode {
public int value;
public BinaryTreeNode left;
public BinaryTreeNode right;
public BinaryTreeNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
*/
public static void mirror_image(BinaryTreeNode root) {
// Write your code here.
}
'use strict';
const fs = require('fs');
const BinaryTreeNode = class {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
};
function output_int32(argument) {
output_write(\`\${argument}\`);
}
function output_BinaryTreeNode_int32(argument) {
let current_level_nodes = [argument];
let current_level_nodes_start = 0;
const nodes_to_print = [];
const print_newlines_before_node_indices = [];
let print_newlines_before_node_indices_start = 0;
while (current_level_nodes.length - current_level_nodes_start > 0) {
const next_level_nodes = [];
while (current_level_nodes.length - current_level_nodes_start > 0) {
const node = current_level_nodes[current_level_nodes_start];
current_level_nodes_start += 1;
nodes_to_print.push(node);
if (node !== null) {
next_level_nodes.push(node.left);
next_level_nodes.push(node.right);
}
}
current_level_nodes = next_level_nodes;
current_level_nodes_start = 0;
print_newlines_before_node_indices.push(nodes_to_print.length);
}
while (nodes_to_print.length > 1 && nodes_to_print[nodes_to_print.length - 1] === null) {
nodes_to_print.pop();
}
output_write("[");
if (nodes_to_print[0] === null) {
output_write("null");
} else {
output_int32(nodes_to_print[0].value);
}
for (let i = 1; i < nodes_to_print.length; i++) {
if (i == print_newlines_before_node_indices[print_newlines_before_node_indices_start]) {
output_write(",\n");
print_newlines_before_node_indices_start += 1
} else {
output_write(", ");
}
if (nodes_to_print[i] === null) {
output_write("null");
} else {
output_int32(nodes_to_print[i].value);
}
}
output_write("]");
}
function input_int32(data) {
const argument = parseInt(data);
if (argument === undefined || isNaN(argument)) {
throw TypeError();
}
return argument;
}
function input_BinaryTreeNode_int32(data) {
let argument = null; // Root of the tree that we return.
const nodes_with_uninitialized_children = [];
let nodes_with_uninitialized_children_start = 0;
let next_child_is_left = true;
for (let i = 0; i < data.length; i++) {
let new_node = null;
if (data[i] !== null) {
new_node = new BinaryTreeNode(input_int32(data[i]));
if (argument === null) {
argument = new_node;
}
}
if (nodes_with_uninitialized_children.length - nodes_with_uninitialized_children_start > 0) {
const parent_node = nodes_with_uninitialized_children[nodes_with_uninitialized_children_start];
nodes_with_uninitialized_children_start += 1;
if (next_child_is_left) {
parent_node.left = new_node;
} else {
parent_node.right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node !== null) {
nodes_with_uninitialized_children.push(new_node);
nodes_with_uninitialized_children.push(new_node);
}
}
return argument;
}
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function(input_stdin) {
input_string += input_stdin;
});
process.stdin.on('end', function() {
main();
});
function output_write(x) {
output_string += x;
}
let input_string = '';
let output_string = '';
function main() {
var root;
try {
const data = JSON.parse(input_string);
root = input_BinaryTreeNode_int32(data['root']);
} catch (err) {
process.stderr.write("reading-input-failed-json\n");
process.stderr.write(err.stack);
throw err;
}
const original_out = process.stdout.write;
process.stdout.write = process.stderr.write.bind(process.stderr);
mirror_image(root);
const result = root;
process.stdout.write = original_out.bind(process.stdout);
if (!(result instanceof BinaryTreeNode) && result !== null) {
throw \`-------- You returned a value of type '\${typeof(result)}' \` +
\`instead of 'BinaryTreeNode'. --------\`;
}
if (result !== null) {
let remaining_nodes = [result];
let number_of_nodes = 0;
while (remaining_nodes.length) {
number_of_nodes++;
if (number_of_nodes > 2000000) {
break;
}
const node = remaining_nodes.pop();
if (node.left !== null) {
remaining_nodes.push(node.left);
}
if (node.right !== null) {
remaining_nodes.push(node.right);
}
}
if (number_of_nodes > 2000000) {
throw '-------- You returned a tree with either a cycle or too many nodes --------';
}
}
output_BinaryTreeNode_int32(result);
output_write("\n");
process.stdout.write(output_string);
}
/*
For your reference:
const BinaryTreeNode = class {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
};
*/
/**
* @param {BinaryTreeNode_int32} root
*/
function mirror_image(root) {
// Write your code here.
}
import java.io._
import java.math._
import java.security._
import java.text._
import java.util._
import java.util.concurrent._
import java.util.function._
import java.util.regex._
import java.util.stream._
import scala.collection.concurrent._
import scala.collection.immutable._
import scala.collection.mutable._
import scala.concurrent._
import scala.io._
import scala.jdk.CollectionConverters._
import scala.math._
import scala.reflect._
import scala.sys._
import scala.util.matching._
import org.json._
class BinaryTreeNode(val value: Int) {
var left: BinaryTreeNode = null
var right: BinaryTreeNode = null
}
object Solution {
}
object Main {
def output_int32(argument: Int): Unit = {
output_write(argument.toString)
}
def output_BinaryTreeNode_int32(argument: BinaryTreeNode): Unit = {
var current_level_nodes = new java.util.LinkedList[BinaryTreeNode]()
current_level_nodes.addLast(argument)
var nodes_to_print = new ArrayList[BinaryTreeNode]()
var print_newlines_before_node_indices = new java.util.LinkedList[Integer]()
while (!current_level_nodes.isEmpty()) {
var next_level_nodes = new java.util.LinkedList[BinaryTreeNode]()
while (!current_level_nodes.isEmpty()) {
var node = current_level_nodes.removeFirst()
nodes_to_print.add(node)
if (node != null) {
next_level_nodes.add(node.left)
next_level_nodes.add(node.right)
}
}
current_level_nodes = next_level_nodes
print_newlines_before_node_indices.add(nodes_to_print.size())
}
while (nodes_to_print.size() > 1 && nodes_to_print.get(nodes_to_print.size() - 1) == null) {
nodes_to_print.remove(nodes_to_print.size() - 1)
}
output_write("[")
if (nodes_to_print.get(0) == null) {
output_write("null")
} else {
output_int32(nodes_to_print.get(0).value)
}
for (i <- 1 until nodes_to_print.size) {
if (i == print_newlines_before_node_indices.getFirst()) {
output_write(",\n")
print_newlines_before_node_indices.removeFirst()
} else {
output_write(", ")
}
if (nodes_to_print.get(i) == null) {
output_write("null")
} else {
output_int32(nodes_to_print.get(i).value)
}
}
output_write("]")
}
def input_int32(data: Any): Int = {
val argument = data.asInstanceOf[Int]
return argument
}
def input_BinaryTreeNode_int32(data: Any): BinaryTreeNode = {
var json_array = data.asInstanceOf[JSONArray]
var argument: BinaryTreeNode = null // Root of the tree that we return.
var nodes_with_uninitialized_children = new java.util.LinkedList[BinaryTreeNode]()
var next_child_is_left = true
var i = json_array.iterator()
while (i.hasNext()) {
var json_array_item = i.next()
var new_node: BinaryTreeNode = null
if (!JSONObject.NULL.equals(json_array_item)) {
new_node = new BinaryTreeNode(input_int32(json_array_item))
if (argument == null) {
argument = new_node
}
}
if (!nodes_with_uninitialized_children.isEmpty()) {
var parent_node: BinaryTreeNode = nodes_with_uninitialized_children.removeFirst()
if (next_child_is_left) {
parent_node.left = new_node
} else {
parent_node.right = new_node
}
next_child_is_left = !next_child_is_left
}
if (new_node != null) {
nodes_with_uninitialized_children.addLast(new_node)
nodes_with_uninitialized_children.addLast(new_node)
}
}
return argument
}
def output_write(x: String) = {
output_string ++= x
}
val output_string = new StringBuilder("")
def main(args: Array[String]) = {
var root: BinaryTreeNode = null
try {
var ok = true
var json_string = new StringBuilder()
val bufferedReader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
while (ok) {
val line = bufferedReader.readLine()
json_string = json_string.append(line)
ok = line != null
}
var data = new JSONObject(json_string.toString)
root = input_BinaryTreeNode_int32(data.get("root"))
} catch {
case ex: Exception => {
System.err.println("reading-input-failed-json")
ex.printStackTrace()
throw ex
}
}
val original_out = System.out
System.setOut(System.err)
Solution.mirror_image(root)
val result = root
System.setOut(original_out)
if (result != null) {
var remaining_nodes = new java.util.ArrayList[BinaryTreeNode]()
remaining_nodes.add(result)
var number_of_nodes: Integer = 0
while (!remaining_nodes.isEmpty() && number_of_nodes <= 2000000) {
number_of_nodes += 1
var node = remaining_nodes.get(remaining_nodes.size() - 1)
remaining_nodes.remove(remaining_nodes.size() - 1)
if (node.left != null) {
remaining_nodes.add(node.left)
}
if (node.right != null) {
remaining_nodes.add(node.right)
}
}
if (number_of_nodes > 2000000) {
throw new RuntimeException("-------- You returned a tree with either a cycle or too many nodes --------")
}
}
output_BinaryTreeNode_int32(result)
output_write("\n")
System.out.print(output_string)
}
}
/*
For your reference:
class BinaryTreeNode(val value: Int) {
var left: BinaryTreeNode = null
var right: BinaryTreeNode = null
}
*/
def mirror_image(root: BinaryTreeNode) = {
// Write your code here.
}
import Foundation
final class BinaryTreeNode {
var value: Int
var left: BinaryTreeNode?
var right: BinaryTreeNode?
public init(value: Int) {
self.value = value
}
}
func output_int32(argument: Int) -> () {
output_write(x: String(argument))
}
func output_BinaryTreeNode_int32(argument: BinaryTreeNode?) -> () {
var current_level_nodes: [BinaryTreeNode?] = [argument]
var current_level_nodes_start = 0
var nodes_to_print: [BinaryTreeNode?] = []
var print_newlines_before_node_indices: [Int] = []
var print_newlines_before_node_indices_start = 0
while current_level_nodes.count - current_level_nodes_start > 0 {
var next_level_nodes: [BinaryTreeNode?] = []
while current_level_nodes.count - current_level_nodes_start > 0 {
let node: BinaryTreeNode? = current_level_nodes[current_level_nodes_start]
current_level_nodes_start += 1
nodes_to_print.append(node)
if node != nil {
next_level_nodes.append(node!.left)
next_level_nodes.append(node!.right)
}
}
current_level_nodes = next_level_nodes
current_level_nodes_start = 0
print_newlines_before_node_indices.append(nodes_to_print.count)
}
while nodes_to_print.count > 1 && nodes_to_print[nodes_to_print.count - 1] == nil {
nodes_to_print.removeLast()
}
output_write(x: "[")
if nodes_to_print[0] == nil {
output_write(x: "null")
} else {
output_int32(argument: nodes_to_print[0]!.value)
}
for (i, node) in nodes_to_print.enumerated() {
if i == 0 {
continue
}
if i == print_newlines_before_node_indices[print_newlines_before_node_indices_start] {
output_write(x: ",\n")
print_newlines_before_node_indices_start += 1
} else {
output_write(x: ", ")
}
if nodes_to_print[i] == nil {
output_write(x: "null")
} else {
output_int32(argument: nodes_to_print[i]!.value)
}
}
output_write(x: "]")
}
func input_int32(data:Any) -> Int {
let argument = (data as! NSNumber).intValue
return argument
}
func input_BinaryTreeNode_int32(data:Any) -> BinaryTreeNode? {
let json_array = data as! [Any?]
var argument: BinaryTreeNode! = nil // Root of the tree that we return.
var nodes_with_uninitialized_children: [BinaryTreeNode] = []
var nodes_with_uninitialized_children_start = 0
var next_child_is_left = true
for json_array_item in json_array {
var new_node: BinaryTreeNode! = nil
if !(json_array_item is NSNull) {
new_node = BinaryTreeNode(value: input_int32(data: json_array_item!))
if argument == nil {
argument = new_node
}
}
if nodes_with_uninitialized_children.count - nodes_with_uninitialized_children_start > 0 {
let parent_node = nodes_with_uninitialized_children[nodes_with_uninitialized_children_start]
nodes_with_uninitialized_children_start += 1
if next_child_is_left {
parent_node.left = new_node
} else {
parent_node.right = new_node
}
next_child_is_left = !next_child_is_left
}
if new_node != nil {
nodes_with_uninitialized_children.append(new_node)
nodes_with_uninitialized_children.append(new_node)
}
}
return argument
}
func output_write(x: String) -> () {
output_string += x
}
struct EncodableString {
let s: String
}
extension EncodableString : Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(s)
}
}
var output_string = ""
let encoder = JSONEncoder()
encoder.outputFormatting = .withoutEscapingSlashes
var root: BinaryTreeNode?
let file_content = FileHandle.standardInput.readDataToEndOfFile()
let data = try JSONSerialization.jsonObject(with: file_content, options: []) as! [String: Any]
root = input_BinaryTreeNode_int32(data: data["root"]!)
var original_out = stdout
stdout = stderr
mirror_image(root: root)
let result = root
stdout = original_out
if result != nil {
var remaining_nodes = [result]
var number_of_nodes = 0
while !remaining_nodes.isEmpty {
number_of_nodes += 1
if number_of_nodes > 2000000 {
break
}
let node: BinaryTreeNode = remaining_nodes.removeLast()!
if node.left != nil {
remaining_nodes.append(node.left)
}
if node.right != nil {
remaining_nodes.append(node.right)
}
}
if number_of_nodes > 2000000 {
fatalError("-------- You returned a tree with either a cycle or too many nodes --------")
}
}
output_BinaryTreeNode_int32(argument: result)
output_write(x: "\n")
print(output_string, terminator:"")
/*
For your reference:
final class BinaryTreeNode {
var value: Int
var left: BinaryTreeNode?
var right: BinaryTreeNode?
public init(value: Int) {
self.value = value
}
}
*/
func mirror_image(root: BinaryTreeNode?) -> Void {
// Write your code here.
}
#!/bin/ruby
require 'json'
require 'stringio'
class BinaryTreeNode
attr_accessor :value, :left, :right
def initialize value
@value = value
@left = nil
@right = nil
end
end
def output_int32(argument)
print(argument)
end
def output_BinaryTreeNode_int32(argument)
current_level_nodes = [argument]
nodes_to_print = []
print_newlines_before_node_indices = []
while not current_level_nodes.empty?
next_level_nodes = []
while not current_level_nodes.empty?
node = current_level_nodes.shift
nodes_to_print.push(node)
if node != nil
next_level_nodes.push(node.left)
next_level_nodes.push(node.right)
end
end
current_level_nodes = next_level_nodes
print_newlines_before_node_indices.push(nodes_to_print.length)
end
while nodes_to_print.length > 1 and nodes_to_print.last.nil?
nodes_to_print.pop()
end
print('[')
if nodes_to_print.first.nil?
print('null')
else
output_int32(nodes_to_print.first.value)
end
for i in (1...nodes_to_print.length)
if i == print_newlines_before_node_indices.first
print(",\n")
print_newlines_before_node_indices.shift()
else
print(', ')
end
if nodes_to_print[i] == nil
print('null')
else
output_int32(nodes_to_print[i].value)
end
end
print(']')
end
def input_int32(data)
argument = Integer(data)
return argument
end
def input_BinaryTreeNode_int32(data)
argument = nil # Root of the tree that we return.
nodes_with_uninitialized_children = []
next_child_is_left = true
for json_array_item in data
if json_array_item.nil?
new_node = nil
else
new_node = BinaryTreeNode.new input_int32 json_array_item
if argument.nil?
argument = new_node
end
end
if not nodes_with_uninitialized_children.empty?
parent_node = nodes_with_uninitialized_children.shift
if next_child_is_left
parent_node.left = new_node
else
parent_node.right = new_node
end
next_child_is_left = !next_child_is_left
end
if not new_node.nil?
nodes_with_uninitialized_children.push(new_node, new_node)
end
end
return argument
end
if __FILE__ == \$0
begin
data = JSON.load(ARGF.read())
root = input_BinaryTreeNode_int32(data['root'])
rescue => err
STDERR.puts("reading-input-failed-json")
STDERR.puts(err)
raise err
end
original_out = \$stdout.dup
\$stdout.reopen(\$stderr.dup)
mirror_image(root)
result = root
\$stdout.reopen(original_out)
if not result.instance_of?(BinaryTreeNode) and result
raise TypeError, "-------- You returned a value of type '#{result.class}' " +
"instead of 'BinaryTreeNode'. --------"
end
if not result.nil?
remaining_nodes = [result]
number_of_nodes = 0
while not remaining_nodes.empty?
number_of_nodes += 1
if number_of_nodes > 2000000
break
end
node = remaining_nodes.pop()
if node.left
remaining_nodes.push(node.left)
end
if node.right
remaining_nodes.push(node.right)
end
end
if number_of_nodes > 2000000
raise TypeError, "-------- You returned a tree with either a cycle or too many nodes --------"
end
end
output_BinaryTreeNode_int32(result)
print("\n")
end
=begin
For your reference:
class BinaryTreeNode
attr_accessor :value, :left, :right
def initialize value
@value = value
@left = nil
@right = nil
end
end
=end
# @param {BinaryTreeNode_int32} root
def mirror_image(root)
# Write your code here.
end
#!/usr/bin/env python
import json
import math
import os
import random
import re
import sys
import traceback
from collections import deque
sys.setrecursionlimit(2000009)
class BinaryTreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def output_int32(argument):
sys.stdout.write(f'{argument}')
def output_BinaryTreeNode_int32(argument):
current_level_nodes = deque([argument])
nodes_to_print = []
print_newlines_before_node_indices = deque()
while current_level_nodes:
next_level_nodes = deque()
while current_level_nodes:
node = current_level_nodes.popleft()
nodes_to_print.append(node)
if node is not None:
next_level_nodes.append(node.left)
next_level_nodes.append(node.right)
current_level_nodes = next_level_nodes
print_newlines_before_node_indices.append(len(nodes_to_print))
while len(nodes_to_print) > 1 and nodes_to_print[-1] is None:
nodes_to_print.pop()
sys.stdout.write('[')
if nodes_to_print[0] is None:
sys.stdout.write('null')
else:
output_int32(nodes_to_print[0].value)
for i in range(1, len(nodes_to_print)):
if i == print_newlines_before_node_indices[0]:
sys.stdout.write(',\n')
print_newlines_before_node_indices.popleft()
else:
sys.stdout.write(', ')
if nodes_to_print[i] is None:
sys.stdout.write('null')
else:
output_int32(nodes_to_print[i].value)
sys.stdout.write(']')
def input_int32(data):
argument = int(data)
return argument
def input_BinaryTreeNode_int32(data):
argument = None # Root of the tree that we return.
nodes_with_uninitialized_children = deque()
next_child_is_left = True
for json_array_item in data:
if json_array_item is None:
new_node = None
else:
new_node = BinaryTreeNode(input_int32(json_array_item))
if argument is None:
argument = new_node
if nodes_with_uninitialized_children:
parent_node = nodes_with_uninitialized_children.popleft()
if next_child_is_left:
parent_node.left = new_node
else:
parent_node.right = new_node
next_child_is_left = not next_child_is_left
if new_node is not None:
nodes_with_uninitialized_children.extend([new_node, new_node])
return argument
if __name__ == '__main__':
try:
data = json.load(sys.stdin)
root = input_BinaryTreeNode_int32(data['root'])
except Exception as ex:
sys.stderr.write('reading-input-failed-json\n')
traceback.print_exc()
raise ex
original_out = sys.stdout
sys.stdout = sys.stderr
mirror_image(root)
result = root
sys.stdout = original_out
if type(result) is not BinaryTreeNode and result is not None:
raise TypeError(f'-------- You returned a value of type "{type(result).__name__}" '
f'instead of "BinaryTreeNode". --------')
if result:
remaining_nodes = [result]
number_of_nodes = 0
while remaining_nodes:
number_of_nodes += 1
if number_of_nodes > 2000000:
break
node = remaining_nodes.pop()
if node.left:
remaining_nodes.append(node.left)
if node.right:
remaining_nodes.append(node.right)
if number_of_nodes > 2000000:
raise TypeError('-------- You returned a tree with either a cycle or too many nodes --------')
output_BinaryTreeNode_int32(result)
sys.stdout.write('\n')
"""
For your reference:
class BinaryTreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
"""
def mirror_image(root):
"""
Args:
root(BinaryTreeNode_int32)
Returns:
Nothing
"""
# Write your code here.
import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import java.util.stream.Collectors.joining
import java.util.stream.Collectors.toList
import org.json.*
class BinaryTreeNode(value: Int) {
var value: Int
var left: BinaryTreeNode?
var right: BinaryTreeNode?
init {
this.value = value
left = null
right = null
}
}
fun output_int32(argument: Int): Unit {
output_string.append(argument)
}
fun output_BinaryTreeNode_int32(argument: BinaryTreeNode?): Unit {
var current_level_nodes: Deque<BinaryTreeNode?> = LinkedList()
current_level_nodes.addLast(argument)
val nodes_to_print: ArrayList<BinaryTreeNode?> = ArrayList()
val print_newlines_before_node_indices: Deque<Int> = LinkedList()
while (!current_level_nodes.isEmpty()) {
val next_level_nodes: Deque<BinaryTreeNode?> = LinkedList()
while (!current_level_nodes.isEmpty()) {
val node: BinaryTreeNode? = current_level_nodes.removeFirst()
nodes_to_print.add(node)
if (node != null) {
next_level_nodes.add(node.left)
next_level_nodes.add(node.right)
}
}
current_level_nodes = next_level_nodes
print_newlines_before_node_indices.add(nodes_to_print.size)
}
while (nodes_to_print.size > 1 && nodes_to_print.get(nodes_to_print.size - 1) == null) {
nodes_to_print.removeAt(nodes_to_print.size - 1)
}
output_string.append('[')
if (nodes_to_print.get(0) == null) {
output_string.append("null")
} else {
output_int32(nodes_to_print.get(0)!!.value)
}
for (i in 1 until nodes_to_print.size) {
if (i == print_newlines_before_node_indices.getFirst()) {
output_string.append(",\n")
print_newlines_before_node_indices.removeFirst()
} else {
output_string.append(", ")
}
if (nodes_to_print.get(i) == null) {
output_string.append("null")
} else {
output_int32(nodes_to_print.get(i)!!.value)
}
}
output_string.append(']')
}
fun input_int32(data: Any): Int {
val argument = data as Int
return argument
}
fun input_BinaryTreeNode_int32(data: Any): BinaryTreeNode? {
val json_array: JSONArray = data as JSONArray
var argument: BinaryTreeNode? = null // Root of the tree that we return.
val nodes_with_uninitialized_children: Deque<BinaryTreeNode> = LinkedList()
var next_child_is_left = true
for (json_array_item in json_array) {
var new_node: BinaryTreeNode? = null
if (!JSONObject.NULL.equals(json_array_item)) {
new_node = BinaryTreeNode(input_int32(json_array_item))
if (argument == null) {
argument = new_node
}
}
if (!nodes_with_uninitialized_children.isEmpty()) {
val parent_node: BinaryTreeNode = nodes_with_uninitialized_children.removeFirst()
if (next_child_is_left) {
parent_node.left = new_node
} else {
parent_node.right = new_node
}
next_child_is_left = !next_child_is_left
}
if (new_node != null) {
nodes_with_uninitialized_children.addLast(new_node)
nodes_with_uninitialized_children.addLast(new_node)
}
}
return argument
}
val float_formatter: DecimalFormat = DecimalFormat("0.00")
val output_string = StringBuilder()
fun main(args: Array<String>) {
var root: BinaryTreeNode?
try {
val json_string = ByteArrayOutputStream()
val buffer = ByteArray(1024)
var length: Int
while (System.\`in\`.read(buffer).also { length = it } != -1) {
json_string.write(buffer, 0, length)
}
val data = JSONObject(json_string.toString("UTF-8"))
root = input_BinaryTreeNode_int32(data.get("root"))
} catch (ex: Exception) {
System.err.println("reading-input-failed-json")
ex.printStackTrace()
throw ex
}
val original_out: PrintStream = System.out
System.setOut(System.err)
mirror_image(root)
val result = root
System.setOut(original_out)
if (result != null) {
val remaining_nodes: ArrayList<BinaryTreeNode> = ArrayList()
remaining_nodes.add(result)
var number_of_nodes = 0
while (!remaining_nodes.isEmpty()) {
number_of_nodes++
if (number_of_nodes > 2000000) {
break
}
val node: BinaryTreeNode = remaining_nodes.get(remaining_nodes.size - 1)
remaining_nodes.removeAt(remaining_nodes.size - 1)
if (node.left != null) {
remaining_nodes.add(node.left!!)
}
if (node.right != null) {
remaining_nodes.add(node.right!!)
}
}
if (number_of_nodes > 2000000) {
throw RuntimeException("-------- You returned a tree with either a cycle or too many nodes --------")
}
}
output_BinaryTreeNode_int32(result)
output_string.append('\n')
System.out.print(output_string.toString())
}
/*
For your reference:
class BinaryTreeNode(value: Int) {
var value: Int
var left: BinaryTreeNode?
var right: BinaryTreeNode?
init {
this.value = value
left = null
right = null
}
}
*/
fun mirror_image(root: BinaryTreeNode?): Unit {
// Write your code here.
}
#include <bits/stdc++.h>
#include <fcntl.h>
#include <unistd.h>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace std;
class BinaryTreeNode {
public:
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
BinaryTreeNode(int value) {
this->value = value;
this->left = nullptr;
this->right = nullptr;
}
};
void output_int32(int argument) {
cout << argument;
}
void output_BinaryTreeNode_int32(BinaryTreeNode *argument) {
deque<BinaryTreeNode *> current_level_nodes = {argument};
vector<BinaryTreeNode *> nodes_to_print;
deque<int> print_newlines_before_node_indices;
while (!current_level_nodes.empty()) {
deque<BinaryTreeNode *> next_level_nodes;
while (!current_level_nodes.empty()) {
BinaryTreeNode *node = current_level_nodes.front();
current_level_nodes.pop_front();
nodes_to_print.push_back(node);
if (node != nullptr) {
next_level_nodes.push_back(node->left);
next_level_nodes.push_back(node->right);
}
}
current_level_nodes = next_level_nodes;
print_newlines_before_node_indices.push_back(nodes_to_print.size());
}
while (nodes_to_print.size() > 1 && nodes_to_print.back() == nullptr) {
nodes_to_print.pop_back();
}
cout << "[";
if (nodes_to_print.front() == nullptr) {
cout << "null";
} else {
output_int32(nodes_to_print.front()->value);
}
for (int i = 1; i < nodes_to_print.size(); i++) {
if (i == print_newlines_before_node_indices.front()) {
cout << ",\n";
print_newlines_before_node_indices.pop_front();
} else {
cout << ", ";
}
if (nodes_to_print.at(i) == nullptr) {
cout << "null";
} else {
output_int32(nodes_to_print.at(i)->value);
}
}
cout << "]";
}
int input_int32(json data) {
int argument = data;
return argument;
}
BinaryTreeNode *input_BinaryTreeNode_int32(json data) {
BinaryTreeNode *argument = nullptr; // Root of the tree that we return.
deque<BinaryTreeNode *> nodes_with_uninitialized_children;
bool next_child_is_left = true;
for (auto json_array_item: data) {
BinaryTreeNode *new_node = nullptr;
if (!json_array_item.is_null()) {
new_node = new BinaryTreeNode(input_int32(json_array_item));
if (argument == nullptr) {
argument = new_node;
}
}
if (!nodes_with_uninitialized_children.empty()) {
BinaryTreeNode *parent_node = nodes_with_uninitialized_children.front();
nodes_with_uninitialized_children.pop_front();
if (next_child_is_left) {
parent_node->left = new_node;
} else {
parent_node->right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node != nullptr) {
nodes_with_uninitialized_children.push_back(new_node);
nodes_with_uninitialized_children.push_back(new_node);
}
}
return argument;
}
int main() {
BinaryTreeNode *root;
try {
string json_string = "";
string line;
while (getline(cin, line)) {
json_string+=line;
}
auto data = json::parse(json_string);
root = input_BinaryTreeNode_int32(data["root"]);
} catch(exception &ex) {
cerr << "reading-input-failed-json" << endl;
cerr << ex.what() << endl;
throw ex;
}
dup2(1, 3);
dup2(2, 1);
mirror_image(root);
BinaryTreeNode *result = root;
fflush(stdout);
dup2(3, 1);
if (result) {
vector<BinaryTreeNode *> remaining_nodes;
remaining_nodes.push_back(result);
int number_of_nodes = 0;
while (!remaining_nodes.empty()) {
number_of_nodes++;
if (number_of_nodes > 2000000) {
break;
}
BinaryTreeNode *node = remaining_nodes.back();
remaining_nodes.pop_back();
if (node->left) {
remaining_nodes.push_back(node->left);
}
if (node->right) {
remaining_nodes.push_back(node->right);
}
}
if (number_of_nodes > 2000000) {
throw runtime_error("-------- You returned a tree with either a cycle or too many nodes --------");
}
}
output_BinaryTreeNode_int32(result);
cout << "\n";
return 0;
}
/*
For your reference:
class BinaryTreeNode {
public:
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
BinaryTreeNode(int value) {
this->value = value;
this->left = nullptr;
this->right = nullptr;
}
};
*/
void mirror_image(BinaryTreeNode *root) {
// Write your code here.
}
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <cjson/cJSON.h>
typedef struct BinaryTreeNode BinaryTreeNode ;
struct BinaryTreeNode {
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
int ik_number_of_nodes = 0;
void ik_count_nodes(BinaryTreeNode *node) {
if (node == NULL) {
return;
}
if (ik_number_of_nodes > 2000000) {
return;
}
ik_number_of_nodes++;
ik_count_nodes(node->left);
ik_count_nodes(node->right);
}
void output_int32(int argument) {
printf("%d", argument);
}
void output_BinaryTreeNode_int32(BinaryTreeNode *argument) {
BinaryTreeNode **current_level_nodes = malloc(ik_number_of_nodes * 3 * sizeof(BinaryTreeNode *));
int current_level_nodes_first = 0;
int current_level_nodes_last = 0;
current_level_nodes[current_level_nodes_last++] = argument;
BinaryTreeNode **nodes_to_print = malloc(ik_number_of_nodes * 3 * sizeof(BinaryTreeNode *));
int nodes_to_print_first = 0;
int nodes_to_print_last = 0;
int *print_newlines_before_node_indices = malloc(ik_number_of_nodes * 3 * sizeof(int));
int print_newlines_before_node_indices_first = 0;
int print_newlines_before_node_indices_last = 0;
while (current_level_nodes_last > current_level_nodes_first) {
BinaryTreeNode **next_level_nodes = malloc(ik_number_of_nodes * 3 * sizeof(BinaryTreeNode *));
int next_level_nodes_first = 0;
int next_level_nodes_last = 0;
while (current_level_nodes_last > current_level_nodes_first) {
BinaryTreeNode *node = current_level_nodes[current_level_nodes_first++];
nodes_to_print[nodes_to_print_last++] = node;
if (node != NULL) {
next_level_nodes[next_level_nodes_last++] = node->left;
next_level_nodes[next_level_nodes_last++] = node->right;
}
}
free(current_level_nodes);
current_level_nodes = next_level_nodes;
current_level_nodes_first = next_level_nodes_first;
current_level_nodes_last = next_level_nodes_last;
print_newlines_before_node_indices[print_newlines_before_node_indices_last++] = nodes_to_print_last - nodes_to_print_first;
}
free(current_level_nodes);
while (((nodes_to_print_last - nodes_to_print_first) > 1) && (nodes_to_print[nodes_to_print_last - 1] == NULL)) {
nodes_to_print_last--;
}
printf("[");
if (nodes_to_print[nodes_to_print_first] == NULL) {
printf("null");
} else {
output_int32(nodes_to_print[nodes_to_print_first]->value);
}
for (int i = nodes_to_print_first + 1; i < nodes_to_print_last; i++) {
if (i == print_newlines_before_node_indices[print_newlines_before_node_indices_first]) {
printf(",\n");
print_newlines_before_node_indices_first++;
} else {
printf(", ");
}
if (nodes_to_print[i] == NULL) {
printf("null");
} else {
output_int32(nodes_to_print[i]->value);
}
}
printf("]");
free(nodes_to_print);
free(print_newlines_before_node_indices);
}
int input_int32(cJSON *data) {
int argument = data->valueint;
return argument;
}
BinaryTreeNode *input_BinaryTreeNode_int32(cJSON *data) {
BinaryTreeNode *argument = NULL; // Root of the tree that we return.
// cJSON_Array: \`child\` points to a linked list of cJSON items that represent values.
cJSON *json_array_item = data->child; // First item in the array.
int n = 0;
while (json_array_item != NULL) {
n++;
json_array_item = json_array_item->next;
}
BinaryTreeNode **nodes_with_uninitialized_children = malloc(n * 3 * sizeof(BinaryTreeNode *));
int nodes_with_uninitialized_children_first = 0;
int nodes_with_uninitialized_children_last = 0;
bool next_child_is_left = true;
json_array_item = data->child; // Back to the first item in the array.
while (json_array_item != NULL) {
BinaryTreeNode *new_node = NULL;
if (!cJSON_IsNull(json_array_item)) {
new_node = malloc(sizeof(BinaryTreeNode));
new_node->value = input_int32(json_array_item);
new_node->left = NULL;
new_node->right = NULL;
if (argument == NULL) {
argument = new_node;
}
}
if (nodes_with_uninitialized_children_last > nodes_with_uninitialized_children_first) {
BinaryTreeNode *parent_node = nodes_with_uninitialized_children[nodes_with_uninitialized_children_first++];
if (next_child_is_left) {
parent_node->left = new_node;
} else {
parent_node->right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node != NULL) {
nodes_with_uninitialized_children[nodes_with_uninitialized_children_last++] = new_node;
nodes_with_uninitialized_children[nodes_with_uninitialized_children_last++] = new_node;
}
json_array_item = json_array_item->next;
}
free(nodes_with_uninitialized_children);
return argument;
}
int main() {
BinaryTreeNode *root;
size_t alloc_length = 1024;
size_t cursor = 0;
signed char *json_string = (signed char *) malloc(alloc_length);
signed char ch;
while ((ch = getchar()) != EOF) {
if (cursor >= alloc_length - 1) {
alloc_length <<= 1;
json_string = realloc(json_string, alloc_length);
}
json_string[cursor++] = ch;
}
json_string[cursor] = '\0';
cursor++;
json_string = realloc(json_string, cursor);
cJSON *data = cJSON_Parse(json_string);
root = input_BinaryTreeNode_int32(cJSON_GetObjectItemCaseSensitive(data, "root"));
dup2(1, 3);
dup2(2, 1);
mirror_image(root);
BinaryTreeNode *result = root;
fflush(stdout);
dup2(3, 1);
ik_count_nodes(result);
if (ik_number_of_nodes > 2000000) {
fprintf(stderr, "-------- You returned a tree with either a cycle or too many nodes --------\n");
return 9;
}
output_BinaryTreeNode_int32(result);
printf("\n");
return 0;
}
/*
For your reference:
typedef struct BinaryTreeNode BinaryTreeNode ;
struct BinaryTreeNode {
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
*/
void mirror_image(BinaryTreeNode *root) {
// Write your code here.
}
Coding problems on trees are asked frequently at tech interviews. Creating a mirror tree from the given binary tree is one such popular DSA problem. Let's look at what the problem entails and how to solve it.
Given the root of a binary tree, transform the tree in-place into its mirror image.
0
/ \
1 2
/ \ / \
3 4 5 6
Output:
0
/ \
2 1
/ \ / \
6 5 4 3
Constraints:
We provided two solutions: a recursive one and an iterative one.
We will refer to the total number of nodes in the given tree as n
.
This is a recursive solution. The main task is to swap left and right children for every node of the tree. We are calling the function recursively and making sure that leaf nodes are handled first then their parents and it goes up to the root node.
O(n).
O(n).
That extra space is used for the call stack.
O(n).
Input is O(n) because we are storing n
nodes relationships and each relationship occupies O(1) space and auxiliary space used is O(n). So, O(n) + O(n) = O(n).
/*
* Asymptotic complexity in terms of number of nodes \`n\` in the given tree:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/
public static void mirror_image(BinaryTreeNode root) {
root = mirror_image_util(root);
}
public static BinaryTreeNode mirror_image_util(BinaryTreeNode root){
if (root == null)
return root;
BinaryTreeNode left = mirror_image_util(root.left);
BinaryTreeNode right = mirror_image_util(root.right);
// Swap the left and right pointers.
root.left = right;
root.right = left;
return root;
}
This solution traverses the tree breadth first using a loop and a queue, without making use of recursion. We initialize the queue with the root node. Then we do the following until the queue is empty:
O(n).
O(n).
We are using a queue for storing nodes to do BFS traversal over the tree. In the worst case scenario, queue size will be n
.
O(n).
Input is O(n) because we are storing n
nodes relationships and each relationship occupies O(1) space and auxiliary space used is O(n). So, O(n) + O(n) = O(n).
/*
* Asymptotic complexity in terms of number of nodes \`n\` in the given tree:
* Time: O(n).
* Auxiliary space: O(n).
* Total space: O(n).
*/
public static void mirror_image(BinaryTreeNode root) {
if (root == null)
return;
Queue<BinaryTreeNode> queue = new LinkedList<BinaryTreeNode>();
queue.add(root);
// Do BFS. While doing BFS, keep swapping
// left and right children
while(!queue.isEmpty()) {
// Pop top node from queue.
BinaryTreeNode cur_node = queue.poll();
// Swap left child with right child.
BinaryTreeNode temp = cur_node.left;
cur_node.left = cur_node.right;
cur_node.right = temp;
// Push left and right children.
if (cur_node.left != null)
queue.add(cur_node.left);
if (cur_node.right != null)
queue.add(cur_node.right);
}
}
We hope that these solutions to creating a mirror image of a binary tree have helped you level up your coding skills. You can expect problems like these at top tech companies like Amazon and Google.
If you are preparing for a tech interview at FAANG or any other Tier-1 tech company, register for Interview Kickstart’s FREE webinar to understand the best way to prepare.
Interview Kickstart offers interview preparation courses taught by FAANG+ tech leads and seasoned hiring managers. Our programs include a comprehensive curriculum, unmatched teaching methods, and career coaching to help you nail your next tech interview.
We offer 17 interview preparation courses, each tailored to a specific engineering domain or role, including the most in-demand and highest-paying domains and roles, such as:
To learn more, register for the FREE webinar.
package main
import (
"bufio"
"bytes"
"container/heap"
"container/list"
"container/ring"
"fmt"
"io"
"math"
"math/rand"
"os"
"encoding/json"
"strconv"
"strings"
"sort"
"unicode"
)
var _ = bufio.ScanBytes
var _ = bytes.Count
var _ = heap.Init
var _ = list.New
var _ = ring.New
var _ = io.EOF
var _ = math.Pow
var _ = rand.Int
var _ = strconv.Atoi
var _ = strings.TrimRight
var _ = sort.Slice
var _ = unicode.IsDigit
type BinaryTreeNode struct {
value int
left *BinaryTreeNode
right *BinaryTreeNode
}
func output_int32(argument int) {
output_write(strconv.Itoa(argument))
}
func output_BinaryTreeNode_int32(argument *BinaryTreeNode) {
current_level_nodes := []*BinaryTreeNode{argument}
current_level_nodes_start := 0
nodes_to_print := make([]*BinaryTreeNode, 0)
print_newlines_before_node_indices := make([]int, 0)
print_newlines_before_node_indices_start := 0
for len(current_level_nodes) - current_level_nodes_start > 0 {
next_level_nodes := make([]*BinaryTreeNode, 0)
for len(current_level_nodes) - current_level_nodes_start > 0 {
node := current_level_nodes[current_level_nodes_start]
current_level_nodes_start += 1
nodes_to_print = append(nodes_to_print, node)
if (node != nil) {
next_level_nodes = append(next_level_nodes, node.left, node.right)
}
}
current_level_nodes = next_level_nodes
current_level_nodes_start = 0
print_newlines_before_node_indices = append(print_newlines_before_node_indices, len(nodes_to_print))
}
for len(nodes_to_print) > 1 && nodes_to_print[len(nodes_to_print) - 1] == nil {
nodes_to_print = nodes_to_print[:len(nodes_to_print) - 1]
}
output_write("[")
if (nodes_to_print[0] == nil) {
output_write("null")
} else {
output_int32(nodes_to_print[0].value)
}
for i := 1; i < len(nodes_to_print); i++ {
if i == print_newlines_before_node_indices[print_newlines_before_node_indices_start] {
output_write(",\n")
print_newlines_before_node_indices_start += 1
} else {
output_write(", ")
}
if (nodes_to_print[i] == nil) {
output_write("null")
} else {
output_int32(nodes_to_print[i].value)
}
}
output_write("]")
}
func input_int32(data interface{}) int {
argument:= int(data.(float64))
return argument
}
func input_BinaryTreeNode_int32(data interface{}) *BinaryTreeNode {
json_array:= data.([]interface{})
json_array_length:= len(json_array)
var argument *BinaryTreeNode // Root of the tree that we return.
nodes_with_uninitialized_children := make([]*BinaryTreeNode, 0)
next_child_is_left := true
for i:= 0; i < int(json_array_length); i++ {
var new_node *BinaryTreeNode
if json_array[i] != nil {
new_node = &BinaryTreeNode {value: input_int32(json_array[i]), left: nil, right: nil,}
if argument == nil {
argument = new_node
}
}
if len(nodes_with_uninitialized_children) > 0 {
parent_node := nodes_with_uninitialized_children[0]
nodes_with_uninitialized_children = nodes_with_uninitialized_children[1:]
if next_child_is_left {
parent_node.left = new_node
} else {
parent_node.right = new_node
}
next_child_is_left = !next_child_is_left
}
if new_node != nil {
nodes_with_uninitialized_children = append(nodes_with_uninitialized_children, new_node, new_node)
}
}
return argument
}
func output_write(x string) {
output_string.WriteString(x)
}
var output_string strings.Builder
func main() {
var root *BinaryTreeNode
var data map[string]interface{}
dec:= json.NewDecoder(os.Stdin)
dec.Decode(&data)
root = input_BinaryTreeNode_int32(data["root"])
var original_out = os.Stdout
os.Stdout = os.Stderr
mirror_image(root)
result:= root
os.Stdout = original_out
if result != nil {
remaining_nodes := []*BinaryTreeNode{result}
number_of_nodes := 0
for len(remaining_nodes) > 0 {
number_of_nodes++
if number_of_nodes > 2000000 {
break
}
node := remaining_nodes[len(remaining_nodes) - 1]
remaining_nodes = remaining_nodes[:len(remaining_nodes) - 1]
if (node.left != nil) {
remaining_nodes = append(remaining_nodes, node.left)
}
if node.right != nil {
remaining_nodes = append(remaining_nodes, node.right)
}
}
if number_of_nodes > 2000000 {
fmt.Fprintf(os.Stderr, "-------- You returned a tree with either a cycle or too many nodes --------\n")
os.Exit(9)
}
}
output_BinaryTreeNode_int32(result)
output_write("\n")
fmt.Print(output_string.String())
}
/*
For your reference:
type BinaryTreeNode struct {
value int
left *BinaryTreeNode
right *BinaryTreeNode
}
*/
func mirror_image(root *BinaryTreeNode) {
// Write your code here.
}
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import org.json.*;
class BinaryTreeNode {
Integer value;
BinaryTreeNode left;
BinaryTreeNode right;
BinaryTreeNode(Integer value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class Solution {
}
class Result {
static void output_int32(Integer argument) {
output_string.append(argument);
}
static void output_BinaryTreeNode_int32(BinaryTreeNode argument) {
Deque<BinaryTreeNode> current_level_nodes = new LinkedList<>();
current_level_nodes.addLast(argument);
ArrayList<BinaryTreeNode> nodes_to_print = new ArrayList<>();
Deque<Integer> print_newlines_before_node_indices = new LinkedList<>();
while (!current_level_nodes.isEmpty()) {
Deque<BinaryTreeNode> next_level_nodes = new LinkedList<>();
while (!current_level_nodes.isEmpty()) {
BinaryTreeNode node = current_level_nodes.removeFirst();
nodes_to_print.add(node);
if (node != null) {
next_level_nodes.add(node.left);
next_level_nodes.add(node.right);
}
}
current_level_nodes = next_level_nodes;
print_newlines_before_node_indices.add(nodes_to_print.size());
}
while (nodes_to_print.size() > 1 && nodes_to_print.get(nodes_to_print.size() - 1) == null) {
nodes_to_print.remove(nodes_to_print.size() - 1);
}
output_string.append('[');
if (nodes_to_print.get(0) == null) {
output_string.append("null");
} else {
output_int32(nodes_to_print.get(0).value);
}
for (int i = 1; i < nodes_to_print.size(); i++) {
if (i == print_newlines_before_node_indices.getFirst()) {
output_string.append(",\n");
print_newlines_before_node_indices.removeFirst();
} else {
output_string.append(", ");
}
if (nodes_to_print.get(i) == null) {
output_string.append("null");
} else {
output_int32(nodes_to_print.get(i).value);
}
}
output_string.append(']');
}
static Integer input_int32(Object data) {
Integer argument = (Integer) data;
return argument;
}
static BinaryTreeNode input_BinaryTreeNode_int32(Object data) {
JSONArray json_array = (JSONArray) data;
BinaryTreeNode argument = null; // Root of the tree that we return.
Deque<BinaryTreeNode> nodes_with_uninitialized_children = new LinkedList<>();
boolean next_child_is_left = true;
for (Object json_array_item: json_array) {
BinaryTreeNode new_node = null;
if (!JSONObject.NULL.equals(json_array_item)) {
new_node = new BinaryTreeNode(input_int32(json_array_item));
if (argument == null) {
argument = new_node;
}
}
if (!nodes_with_uninitialized_children.isEmpty()) {
BinaryTreeNode parent_node = nodes_with_uninitialized_children.removeFirst();
if (next_child_is_left) {
parent_node.left = new_node;
} else {
parent_node.right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node != null) {
nodes_with_uninitialized_children.addLast(new_node);
nodes_with_uninitialized_children.addLast(new_node);
}
}
return argument;
}
private static final DecimalFormat float_formatter = new DecimalFormat("0.00");
private static final StringBuilder output_string = new StringBuilder();
public static void main(String[] args) throws Exception {
BinaryTreeNode root;
try {
ByteArrayOutputStream json_string = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int length; (length = System.in.read(buffer)) != -1; ) {
json_string.write(buffer, 0, length);
}
JSONObject data = new JSONObject(json_string.toString("UTF-8"));
root = input_BinaryTreeNode_int32(data.get("root"));
} catch (Exception ex) {
System.err.println("reading-input-failed-json");
ex.printStackTrace();
throw ex;
}
PrintStream original_out = System.out;
System.setOut(System.err);
Solution.mirror_image(root);
BinaryTreeNode result = root;
System.setOut(original_out);
if (result != null) {
ArrayList<BinaryTreeNode> remaining_nodes = new ArrayList<>();
remaining_nodes.add(result);
int number_of_nodes = 0;
while (!remaining_nodes.isEmpty()) {
number_of_nodes++;
if (number_of_nodes > 2000000) {
break;
}
BinaryTreeNode node = remaining_nodes.get(remaining_nodes.size() - 1);
remaining_nodes.remove(remaining_nodes.size() - 1);
if (node.left != null) {
remaining_nodes.add(node.left);
}
if (node.right != null) {
remaining_nodes.add(node.right);
}
}
if (number_of_nodes > 2000000) {
throw new RuntimeException("-------- You returned a tree with either a cycle or too many nodes --------");
}
}
output_BinaryTreeNode_int32(result);
output_string.append('\n');
System.out.print(output_string.toString());
}
}
/*
For your reference:
class BinaryTreeNode {
Integer value;
BinaryTreeNode left;
BinaryTreeNode right;
BinaryTreeNode(Integer value) {
this.value = value;
this.left = null;
this.right = null;
}
}
*/
static void mirror_image(BinaryTreeNode root) {
// Write your code here.
}
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Json;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.RegularExpressions;
using System.Text;
using System;
class BinaryTreeNode {
public int value;
public BinaryTreeNode left;
public BinaryTreeNode right;
public BinaryTreeNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
class Solution {
}
class Result {
public static void output_int32(int argument) {
textWriter.Write(argument);
}
public static void output_BinaryTreeNode_int32(BinaryTreeNode argument) {
Queue<BinaryTreeNode> current_level_nodes = new Queue<BinaryTreeNode>();
current_level_nodes.Enqueue(argument);
List<BinaryTreeNode> nodes_to_print = new List<BinaryTreeNode>();
Queue<int> print_newlines_before_node_indices = new Queue<int>();
while (current_level_nodes.Count > 0) {
Queue<BinaryTreeNode> next_level_nodes = new Queue<BinaryTreeNode>();
while (current_level_nodes.Count > 0) {
BinaryTreeNode node = current_level_nodes.Dequeue();
nodes_to_print.Add(node);
if (node != null) {
next_level_nodes.Enqueue(node.left);
next_level_nodes.Enqueue(node.right);
}
}
current_level_nodes = next_level_nodes;
print_newlines_before_node_indices.Enqueue(nodes_to_print.Count);
}
while (nodes_to_print.Count > 1 && nodes_to_print[nodes_to_print.Count - 1] == null) {
nodes_to_print.RemoveAt(nodes_to_print.Count - 1);
}
textWriter.Write("[");
if (nodes_to_print[0] == null) {
textWriter.Write("null");
} else {
output_int32(nodes_to_print[0].value);
}
for (int i = 1; i < nodes_to_print.Count; i++) {
if (i == print_newlines_before_node_indices.Peek()) {
textWriter.Write(",\n");
print_newlines_before_node_indices.Dequeue();
} else {
textWriter.Write(", ");
}
if (nodes_to_print[i] == null) {
textWriter.Write("null");
} else {
output_int32(nodes_to_print[i].value);
}
}
textWriter.Write("]");
}
public static int input_int32(Object data) {
int argument = (int) (JsonValue) data;
return argument;
}
public static BinaryTreeNode input_BinaryTreeNode_int32(Object data) {
JsonArray json_array = (JsonArray) data;
BinaryTreeNode argument = null; // Root of the tree that we return.
Queue<BinaryTreeNode> nodes_with_uninitialized_children = new Queue<BinaryTreeNode>();
bool next_child_is_left = true;
foreach (Object json_array_item in json_array) {
BinaryTreeNode new_node = null;
if (json_array_item != null) {
new_node = new BinaryTreeNode(input_int32(json_array_item));
if (argument == null) {
argument = new_node;
}
}
if (nodes_with_uninitialized_children.Count > 0) {
BinaryTreeNode parent_node = nodes_with_uninitialized_children.Dequeue();
if (next_child_is_left) {
parent_node.left = new_node;
} else {
parent_node.right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node != null) {
nodes_with_uninitialized_children.Enqueue(new_node);
nodes_with_uninitialized_children.Enqueue(new_node);
}
}
return argument;
}
public static TextWriter textWriter;
public static void Main(string[] args) {
textWriter = new StreamWriter(Console.OpenStandardOutput());
BinaryTreeNode root;
try {
JsonValue data = JsonValue.Load(new StreamReader(Console.OpenStandardInput()));
root = input_BinaryTreeNode_int32(data["root"]);
} catch (Exception ex) {
Console.Error.WriteLine("reading-input-failed-json");
Console.Error.WriteLine(ex.StackTrace);
throw ex;
}
TextWriter original_out = Console.Out;
Console.SetOut(Console.Error);
Solution.mirror_image(root);
BinaryTreeNode result = root;
Console.SetOut(original_out);
if (result != null) {
List<BinaryTreeNode> remaining_nodes = new List<BinaryTreeNode>();
remaining_nodes.Add(result);
int number_of_nodes = 0;
while (remaining_nodes.Count > 0) {
number_of_nodes++;
if (number_of_nodes > 2000000) {
break;
}
BinaryTreeNode node = remaining_nodes[remaining_nodes.Count - 1];
remaining_nodes.RemoveAt(remaining_nodes.Count - 1);
if (node.left != null) {
remaining_nodes.Add(node.left);
}
if (node.right != null) {
remaining_nodes.Add(node.right);
}
}
if (number_of_nodes > 2000000) {
throw new SystemException("-------- You returned a tree with either a cycle or too many nodes --------");
}
}
output_BinaryTreeNode_int32(result);
textWriter.Write('\n');
textWriter.Flush();
textWriter.Close();
}
}
/*
For your reference:
class BinaryTreeNode {
public int value;
public BinaryTreeNode left;
public BinaryTreeNode right;
public BinaryTreeNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
*/
public static void mirror_image(BinaryTreeNode root) {
// Write your code here.
}
'use strict';
const fs = require('fs');
const BinaryTreeNode = class {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
};
function output_int32(argument) {
output_write(\`\${argument}\`);
}
function output_BinaryTreeNode_int32(argument) {
let current_level_nodes = [argument];
let current_level_nodes_start = 0;
const nodes_to_print = [];
const print_newlines_before_node_indices = [];
let print_newlines_before_node_indices_start = 0;
while (current_level_nodes.length - current_level_nodes_start > 0) {
const next_level_nodes = [];
while (current_level_nodes.length - current_level_nodes_start > 0) {
const node = current_level_nodes[current_level_nodes_start];
current_level_nodes_start += 1;
nodes_to_print.push(node);
if (node !== null) {
next_level_nodes.push(node.left);
next_level_nodes.push(node.right);
}
}
current_level_nodes = next_level_nodes;
current_level_nodes_start = 0;
print_newlines_before_node_indices.push(nodes_to_print.length);
}
while (nodes_to_print.length > 1 && nodes_to_print[nodes_to_print.length - 1] === null) {
nodes_to_print.pop();
}
output_write("[");
if (nodes_to_print[0] === null) {
output_write("null");
} else {
output_int32(nodes_to_print[0].value);
}
for (let i = 1; i < nodes_to_print.length; i++) {
if (i == print_newlines_before_node_indices[print_newlines_before_node_indices_start]) {
output_write(",\n");
print_newlines_before_node_indices_start += 1
} else {
output_write(", ");
}
if (nodes_to_print[i] === null) {
output_write("null");
} else {
output_int32(nodes_to_print[i].value);
}
}
output_write("]");
}
function input_int32(data) {
const argument = parseInt(data);
if (argument === undefined || isNaN(argument)) {
throw TypeError();
}
return argument;
}
function input_BinaryTreeNode_int32(data) {
let argument = null; // Root of the tree that we return.
const nodes_with_uninitialized_children = [];
let nodes_with_uninitialized_children_start = 0;
let next_child_is_left = true;
for (let i = 0; i < data.length; i++) {
let new_node = null;
if (data[i] !== null) {
new_node = new BinaryTreeNode(input_int32(data[i]));
if (argument === null) {
argument = new_node;
}
}
if (nodes_with_uninitialized_children.length - nodes_with_uninitialized_children_start > 0) {
const parent_node = nodes_with_uninitialized_children[nodes_with_uninitialized_children_start];
nodes_with_uninitialized_children_start += 1;
if (next_child_is_left) {
parent_node.left = new_node;
} else {
parent_node.right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node !== null) {
nodes_with_uninitialized_children.push(new_node);
nodes_with_uninitialized_children.push(new_node);
}
}
return argument;
}
process.stdin.resume();
process.stdin.setEncoding('utf-8');
process.stdin.on('data', function(input_stdin) {
input_string += input_stdin;
});
process.stdin.on('end', function() {
main();
});
function output_write(x) {
output_string += x;
}
let input_string = '';
let output_string = '';
function main() {
var root;
try {
const data = JSON.parse(input_string);
root = input_BinaryTreeNode_int32(data['root']);
} catch (err) {
process.stderr.write("reading-input-failed-json\n");
process.stderr.write(err.stack);
throw err;
}
const original_out = process.stdout.write;
process.stdout.write = process.stderr.write.bind(process.stderr);
mirror_image(root);
const result = root;
process.stdout.write = original_out.bind(process.stdout);
if (!(result instanceof BinaryTreeNode) && result !== null) {
throw \`-------- You returned a value of type '\${typeof(result)}' \` +
\`instead of 'BinaryTreeNode'. --------\`;
}
if (result !== null) {
let remaining_nodes = [result];
let number_of_nodes = 0;
while (remaining_nodes.length) {
number_of_nodes++;
if (number_of_nodes > 2000000) {
break;
}
const node = remaining_nodes.pop();
if (node.left !== null) {
remaining_nodes.push(node.left);
}
if (node.right !== null) {
remaining_nodes.push(node.right);
}
}
if (number_of_nodes > 2000000) {
throw '-------- You returned a tree with either a cycle or too many nodes --------';
}
}
output_BinaryTreeNode_int32(result);
output_write("\n");
process.stdout.write(output_string);
}
/*
For your reference:
const BinaryTreeNode = class {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
};
*/
/**
* @param {BinaryTreeNode_int32} root
*/
function mirror_image(root) {
// Write your code here.
}
import java.io._
import java.math._
import java.security._
import java.text._
import java.util._
import java.util.concurrent._
import java.util.function._
import java.util.regex._
import java.util.stream._
import scala.collection.concurrent._
import scala.collection.immutable._
import scala.collection.mutable._
import scala.concurrent._
import scala.io._
import scala.jdk.CollectionConverters._
import scala.math._
import scala.reflect._
import scala.sys._
import scala.util.matching._
import org.json._
class BinaryTreeNode(val value: Int) {
var left: BinaryTreeNode = null
var right: BinaryTreeNode = null
}
object Solution {
}
object Main {
def output_int32(argument: Int): Unit = {
output_write(argument.toString)
}
def output_BinaryTreeNode_int32(argument: BinaryTreeNode): Unit = {
var current_level_nodes = new java.util.LinkedList[BinaryTreeNode]()
current_level_nodes.addLast(argument)
var nodes_to_print = new ArrayList[BinaryTreeNode]()
var print_newlines_before_node_indices = new java.util.LinkedList[Integer]()
while (!current_level_nodes.isEmpty()) {
var next_level_nodes = new java.util.LinkedList[BinaryTreeNode]()
while (!current_level_nodes.isEmpty()) {
var node = current_level_nodes.removeFirst()
nodes_to_print.add(node)
if (node != null) {
next_level_nodes.add(node.left)
next_level_nodes.add(node.right)
}
}
current_level_nodes = next_level_nodes
print_newlines_before_node_indices.add(nodes_to_print.size())
}
while (nodes_to_print.size() > 1 && nodes_to_print.get(nodes_to_print.size() - 1) == null) {
nodes_to_print.remove(nodes_to_print.size() - 1)
}
output_write("[")
if (nodes_to_print.get(0) == null) {
output_write("null")
} else {
output_int32(nodes_to_print.get(0).value)
}
for (i <- 1 until nodes_to_print.size) {
if (i == print_newlines_before_node_indices.getFirst()) {
output_write(",\n")
print_newlines_before_node_indices.removeFirst()
} else {
output_write(", ")
}
if (nodes_to_print.get(i) == null) {
output_write("null")
} else {
output_int32(nodes_to_print.get(i).value)
}
}
output_write("]")
}
def input_int32(data: Any): Int = {
val argument = data.asInstanceOf[Int]
return argument
}
def input_BinaryTreeNode_int32(data: Any): BinaryTreeNode = {
var json_array = data.asInstanceOf[JSONArray]
var argument: BinaryTreeNode = null // Root of the tree that we return.
var nodes_with_uninitialized_children = new java.util.LinkedList[BinaryTreeNode]()
var next_child_is_left = true
var i = json_array.iterator()
while (i.hasNext()) {
var json_array_item = i.next()
var new_node: BinaryTreeNode = null
if (!JSONObject.NULL.equals(json_array_item)) {
new_node = new BinaryTreeNode(input_int32(json_array_item))
if (argument == null) {
argument = new_node
}
}
if (!nodes_with_uninitialized_children.isEmpty()) {
var parent_node: BinaryTreeNode = nodes_with_uninitialized_children.removeFirst()
if (next_child_is_left) {
parent_node.left = new_node
} else {
parent_node.right = new_node
}
next_child_is_left = !next_child_is_left
}
if (new_node != null) {
nodes_with_uninitialized_children.addLast(new_node)
nodes_with_uninitialized_children.addLast(new_node)
}
}
return argument
}
def output_write(x: String) = {
output_string ++= x
}
val output_string = new StringBuilder("")
def main(args: Array[String]) = {
var root: BinaryTreeNode = null
try {
var ok = true
var json_string = new StringBuilder()
val bufferedReader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in))
while (ok) {
val line = bufferedReader.readLine()
json_string = json_string.append(line)
ok = line != null
}
var data = new JSONObject(json_string.toString)
root = input_BinaryTreeNode_int32(data.get("root"))
} catch {
case ex: Exception => {
System.err.println("reading-input-failed-json")
ex.printStackTrace()
throw ex
}
}
val original_out = System.out
System.setOut(System.err)
Solution.mirror_image(root)
val result = root
System.setOut(original_out)
if (result != null) {
var remaining_nodes = new java.util.ArrayList[BinaryTreeNode]()
remaining_nodes.add(result)
var number_of_nodes: Integer = 0
while (!remaining_nodes.isEmpty() && number_of_nodes <= 2000000) {
number_of_nodes += 1
var node = remaining_nodes.get(remaining_nodes.size() - 1)
remaining_nodes.remove(remaining_nodes.size() - 1)
if (node.left != null) {
remaining_nodes.add(node.left)
}
if (node.right != null) {
remaining_nodes.add(node.right)
}
}
if (number_of_nodes > 2000000) {
throw new RuntimeException("-------- You returned a tree with either a cycle or too many nodes --------")
}
}
output_BinaryTreeNode_int32(result)
output_write("\n")
System.out.print(output_string)
}
}
/*
For your reference:
class BinaryTreeNode(val value: Int) {
var left: BinaryTreeNode = null
var right: BinaryTreeNode = null
}
*/
def mirror_image(root: BinaryTreeNode) = {
// Write your code here.
}
import Foundation
final class BinaryTreeNode {
var value: Int
var left: BinaryTreeNode?
var right: BinaryTreeNode?
public init(value: Int) {
self.value = value
}
}
func output_int32(argument: Int) -> () {
output_write(x: String(argument))
}
func output_BinaryTreeNode_int32(argument: BinaryTreeNode?) -> () {
var current_level_nodes: [BinaryTreeNode?] = [argument]
var current_level_nodes_start = 0
var nodes_to_print: [BinaryTreeNode?] = []
var print_newlines_before_node_indices: [Int] = []
var print_newlines_before_node_indices_start = 0
while current_level_nodes.count - current_level_nodes_start > 0 {
var next_level_nodes: [BinaryTreeNode?] = []
while current_level_nodes.count - current_level_nodes_start > 0 {
let node: BinaryTreeNode? = current_level_nodes[current_level_nodes_start]
current_level_nodes_start += 1
nodes_to_print.append(node)
if node != nil {
next_level_nodes.append(node!.left)
next_level_nodes.append(node!.right)
}
}
current_level_nodes = next_level_nodes
current_level_nodes_start = 0
print_newlines_before_node_indices.append(nodes_to_print.count)
}
while nodes_to_print.count > 1 && nodes_to_print[nodes_to_print.count - 1] == nil {
nodes_to_print.removeLast()
}
output_write(x: "[")
if nodes_to_print[0] == nil {
output_write(x: "null")
} else {
output_int32(argument: nodes_to_print[0]!.value)
}
for (i, node) in nodes_to_print.enumerated() {
if i == 0 {
continue
}
if i == print_newlines_before_node_indices[print_newlines_before_node_indices_start] {
output_write(x: ",\n")
print_newlines_before_node_indices_start += 1
} else {
output_write(x: ", ")
}
if nodes_to_print[i] == nil {
output_write(x: "null")
} else {
output_int32(argument: nodes_to_print[i]!.value)
}
}
output_write(x: "]")
}
func input_int32(data:Any) -> Int {
let argument = (data as! NSNumber).intValue
return argument
}
func input_BinaryTreeNode_int32(data:Any) -> BinaryTreeNode? {
let json_array = data as! [Any?]
var argument: BinaryTreeNode! = nil // Root of the tree that we return.
var nodes_with_uninitialized_children: [BinaryTreeNode] = []
var nodes_with_uninitialized_children_start = 0
var next_child_is_left = true
for json_array_item in json_array {
var new_node: BinaryTreeNode! = nil
if !(json_array_item is NSNull) {
new_node = BinaryTreeNode(value: input_int32(data: json_array_item!))
if argument == nil {
argument = new_node
}
}
if nodes_with_uninitialized_children.count - nodes_with_uninitialized_children_start > 0 {
let parent_node = nodes_with_uninitialized_children[nodes_with_uninitialized_children_start]
nodes_with_uninitialized_children_start += 1
if next_child_is_left {
parent_node.left = new_node
} else {
parent_node.right = new_node
}
next_child_is_left = !next_child_is_left
}
if new_node != nil {
nodes_with_uninitialized_children.append(new_node)
nodes_with_uninitialized_children.append(new_node)
}
}
return argument
}
func output_write(x: String) -> () {
output_string += x
}
struct EncodableString {
let s: String
}
extension EncodableString : Encodable {
func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(s)
}
}
var output_string = ""
let encoder = JSONEncoder()
encoder.outputFormatting = .withoutEscapingSlashes
var root: BinaryTreeNode?
let file_content = FileHandle.standardInput.readDataToEndOfFile()
let data = try JSONSerialization.jsonObject(with: file_content, options: []) as! [String: Any]
root = input_BinaryTreeNode_int32(data: data["root"]!)
var original_out = stdout
stdout = stderr
mirror_image(root: root)
let result = root
stdout = original_out
if result != nil {
var remaining_nodes = [result]
var number_of_nodes = 0
while !remaining_nodes.isEmpty {
number_of_nodes += 1
if number_of_nodes > 2000000 {
break
}
let node: BinaryTreeNode = remaining_nodes.removeLast()!
if node.left != nil {
remaining_nodes.append(node.left)
}
if node.right != nil {
remaining_nodes.append(node.right)
}
}
if number_of_nodes > 2000000 {
fatalError("-------- You returned a tree with either a cycle or too many nodes --------")
}
}
output_BinaryTreeNode_int32(argument: result)
output_write(x: "\n")
print(output_string, terminator:"")
/*
For your reference:
final class BinaryTreeNode {
var value: Int
var left: BinaryTreeNode?
var right: BinaryTreeNode?
public init(value: Int) {
self.value = value
}
}
*/
func mirror_image(root: BinaryTreeNode?) -> Void {
// Write your code here.
}
#!/bin/ruby
require 'json'
require 'stringio'
class BinaryTreeNode
attr_accessor :value, :left, :right
def initialize value
@value = value
@left = nil
@right = nil
end
end
def output_int32(argument)
print(argument)
end
def output_BinaryTreeNode_int32(argument)
current_level_nodes = [argument]
nodes_to_print = []
print_newlines_before_node_indices = []
while not current_level_nodes.empty?
next_level_nodes = []
while not current_level_nodes.empty?
node = current_level_nodes.shift
nodes_to_print.push(node)
if node != nil
next_level_nodes.push(node.left)
next_level_nodes.push(node.right)
end
end
current_level_nodes = next_level_nodes
print_newlines_before_node_indices.push(nodes_to_print.length)
end
while nodes_to_print.length > 1 and nodes_to_print.last.nil?
nodes_to_print.pop()
end
print('[')
if nodes_to_print.first.nil?
print('null')
else
output_int32(nodes_to_print.first.value)
end
for i in (1...nodes_to_print.length)
if i == print_newlines_before_node_indices.first
print(",\n")
print_newlines_before_node_indices.shift()
else
print(', ')
end
if nodes_to_print[i] == nil
print('null')
else
output_int32(nodes_to_print[i].value)
end
end
print(']')
end
def input_int32(data)
argument = Integer(data)
return argument
end
def input_BinaryTreeNode_int32(data)
argument = nil # Root of the tree that we return.
nodes_with_uninitialized_children = []
next_child_is_left = true
for json_array_item in data
if json_array_item.nil?
new_node = nil
else
new_node = BinaryTreeNode.new input_int32 json_array_item
if argument.nil?
argument = new_node
end
end
if not nodes_with_uninitialized_children.empty?
parent_node = nodes_with_uninitialized_children.shift
if next_child_is_left
parent_node.left = new_node
else
parent_node.right = new_node
end
next_child_is_left = !next_child_is_left
end
if not new_node.nil?
nodes_with_uninitialized_children.push(new_node, new_node)
end
end
return argument
end
if __FILE__ == \$0
begin
data = JSON.load(ARGF.read())
root = input_BinaryTreeNode_int32(data['root'])
rescue => err
STDERR.puts("reading-input-failed-json")
STDERR.puts(err)
raise err
end
original_out = \$stdout.dup
\$stdout.reopen(\$stderr.dup)
mirror_image(root)
result = root
\$stdout.reopen(original_out)
if not result.instance_of?(BinaryTreeNode) and result
raise TypeError, "-------- You returned a value of type '#{result.class}' " +
"instead of 'BinaryTreeNode'. --------"
end
if not result.nil?
remaining_nodes = [result]
number_of_nodes = 0
while not remaining_nodes.empty?
number_of_nodes += 1
if number_of_nodes > 2000000
break
end
node = remaining_nodes.pop()
if node.left
remaining_nodes.push(node.left)
end
if node.right
remaining_nodes.push(node.right)
end
end
if number_of_nodes > 2000000
raise TypeError, "-------- You returned a tree with either a cycle or too many nodes --------"
end
end
output_BinaryTreeNode_int32(result)
print("\n")
end
=begin
For your reference:
class BinaryTreeNode
attr_accessor :value, :left, :right
def initialize value
@value = value
@left = nil
@right = nil
end
end
=end
# @param {BinaryTreeNode_int32} root
def mirror_image(root)
# Write your code here.
end
#!/usr/bin/env python
import json
import math
import os
import random
import re
import sys
import traceback
from collections import deque
sys.setrecursionlimit(2000009)
class BinaryTreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def output_int32(argument):
sys.stdout.write(f'{argument}')
def output_BinaryTreeNode_int32(argument):
current_level_nodes = deque([argument])
nodes_to_print = []
print_newlines_before_node_indices = deque()
while current_level_nodes:
next_level_nodes = deque()
while current_level_nodes:
node = current_level_nodes.popleft()
nodes_to_print.append(node)
if node is not None:
next_level_nodes.append(node.left)
next_level_nodes.append(node.right)
current_level_nodes = next_level_nodes
print_newlines_before_node_indices.append(len(nodes_to_print))
while len(nodes_to_print) > 1 and nodes_to_print[-1] is None:
nodes_to_print.pop()
sys.stdout.write('[')
if nodes_to_print[0] is None:
sys.stdout.write('null')
else:
output_int32(nodes_to_print[0].value)
for i in range(1, len(nodes_to_print)):
if i == print_newlines_before_node_indices[0]:
sys.stdout.write(',\n')
print_newlines_before_node_indices.popleft()
else:
sys.stdout.write(', ')
if nodes_to_print[i] is None:
sys.stdout.write('null')
else:
output_int32(nodes_to_print[i].value)
sys.stdout.write(']')
def input_int32(data):
argument = int(data)
return argument
def input_BinaryTreeNode_int32(data):
argument = None # Root of the tree that we return.
nodes_with_uninitialized_children = deque()
next_child_is_left = True
for json_array_item in data:
if json_array_item is None:
new_node = None
else:
new_node = BinaryTreeNode(input_int32(json_array_item))
if argument is None:
argument = new_node
if nodes_with_uninitialized_children:
parent_node = nodes_with_uninitialized_children.popleft()
if next_child_is_left:
parent_node.left = new_node
else:
parent_node.right = new_node
next_child_is_left = not next_child_is_left
if new_node is not None:
nodes_with_uninitialized_children.extend([new_node, new_node])
return argument
if __name__ == '__main__':
try:
data = json.load(sys.stdin)
root = input_BinaryTreeNode_int32(data['root'])
except Exception as ex:
sys.stderr.write('reading-input-failed-json\n')
traceback.print_exc()
raise ex
original_out = sys.stdout
sys.stdout = sys.stderr
mirror_image(root)
result = root
sys.stdout = original_out
if type(result) is not BinaryTreeNode and result is not None:
raise TypeError(f'-------- You returned a value of type "{type(result).__name__}" '
f'instead of "BinaryTreeNode". --------')
if result:
remaining_nodes = [result]
number_of_nodes = 0
while remaining_nodes:
number_of_nodes += 1
if number_of_nodes > 2000000:
break
node = remaining_nodes.pop()
if node.left:
remaining_nodes.append(node.left)
if node.right:
remaining_nodes.append(node.right)
if number_of_nodes > 2000000:
raise TypeError('-------- You returned a tree with either a cycle or too many nodes --------')
output_BinaryTreeNode_int32(result)
sys.stdout.write('\n')
"""
For your reference:
class BinaryTreeNode:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
"""
def mirror_image(root):
"""
Args:
root(BinaryTreeNode_int32)
Returns:
Nothing
"""
# Write your code here.
import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import java.util.stream.Collectors.joining
import java.util.stream.Collectors.toList
import org.json.*
class BinaryTreeNode(value: Int) {
var value: Int
var left: BinaryTreeNode?
var right: BinaryTreeNode?
init {
this.value = value
left = null
right = null
}
}
fun output_int32(argument: Int): Unit {
output_string.append(argument)
}
fun output_BinaryTreeNode_int32(argument: BinaryTreeNode?): Unit {
var current_level_nodes: Deque<BinaryTreeNode?> = LinkedList()
current_level_nodes.addLast(argument)
val nodes_to_print: ArrayList<BinaryTreeNode?> = ArrayList()
val print_newlines_before_node_indices: Deque<Int> = LinkedList()
while (!current_level_nodes.isEmpty()) {
val next_level_nodes: Deque<BinaryTreeNode?> = LinkedList()
while (!current_level_nodes.isEmpty()) {
val node: BinaryTreeNode? = current_level_nodes.removeFirst()
nodes_to_print.add(node)
if (node != null) {
next_level_nodes.add(node.left)
next_level_nodes.add(node.right)
}
}
current_level_nodes = next_level_nodes
print_newlines_before_node_indices.add(nodes_to_print.size)
}
while (nodes_to_print.size > 1 && nodes_to_print.get(nodes_to_print.size - 1) == null) {
nodes_to_print.removeAt(nodes_to_print.size - 1)
}
output_string.append('[')
if (nodes_to_print.get(0) == null) {
output_string.append("null")
} else {
output_int32(nodes_to_print.get(0)!!.value)
}
for (i in 1 until nodes_to_print.size) {
if (i == print_newlines_before_node_indices.getFirst()) {
output_string.append(",\n")
print_newlines_before_node_indices.removeFirst()
} else {
output_string.append(", ")
}
if (nodes_to_print.get(i) == null) {
output_string.append("null")
} else {
output_int32(nodes_to_print.get(i)!!.value)
}
}
output_string.append(']')
}
fun input_int32(data: Any): Int {
val argument = data as Int
return argument
}
fun input_BinaryTreeNode_int32(data: Any): BinaryTreeNode? {
val json_array: JSONArray = data as JSONArray
var argument: BinaryTreeNode? = null // Root of the tree that we return.
val nodes_with_uninitialized_children: Deque<BinaryTreeNode> = LinkedList()
var next_child_is_left = true
for (json_array_item in json_array) {
var new_node: BinaryTreeNode? = null
if (!JSONObject.NULL.equals(json_array_item)) {
new_node = BinaryTreeNode(input_int32(json_array_item))
if (argument == null) {
argument = new_node
}
}
if (!nodes_with_uninitialized_children.isEmpty()) {
val parent_node: BinaryTreeNode = nodes_with_uninitialized_children.removeFirst()
if (next_child_is_left) {
parent_node.left = new_node
} else {
parent_node.right = new_node
}
next_child_is_left = !next_child_is_left
}
if (new_node != null) {
nodes_with_uninitialized_children.addLast(new_node)
nodes_with_uninitialized_children.addLast(new_node)
}
}
return argument
}
val float_formatter: DecimalFormat = DecimalFormat("0.00")
val output_string = StringBuilder()
fun main(args: Array<String>) {
var root: BinaryTreeNode?
try {
val json_string = ByteArrayOutputStream()
val buffer = ByteArray(1024)
var length: Int
while (System.\`in\`.read(buffer).also { length = it } != -1) {
json_string.write(buffer, 0, length)
}
val data = JSONObject(json_string.toString("UTF-8"))
root = input_BinaryTreeNode_int32(data.get("root"))
} catch (ex: Exception) {
System.err.println("reading-input-failed-json")
ex.printStackTrace()
throw ex
}
val original_out: PrintStream = System.out
System.setOut(System.err)
mirror_image(root)
val result = root
System.setOut(original_out)
if (result != null) {
val remaining_nodes: ArrayList<BinaryTreeNode> = ArrayList()
remaining_nodes.add(result)
var number_of_nodes = 0
while (!remaining_nodes.isEmpty()) {
number_of_nodes++
if (number_of_nodes > 2000000) {
break
}
val node: BinaryTreeNode = remaining_nodes.get(remaining_nodes.size - 1)
remaining_nodes.removeAt(remaining_nodes.size - 1)
if (node.left != null) {
remaining_nodes.add(node.left!!)
}
if (node.right != null) {
remaining_nodes.add(node.right!!)
}
}
if (number_of_nodes > 2000000) {
throw RuntimeException("-------- You returned a tree with either a cycle or too many nodes --------")
}
}
output_BinaryTreeNode_int32(result)
output_string.append('\n')
System.out.print(output_string.toString())
}
/*
For your reference:
class BinaryTreeNode(value: Int) {
var value: Int
var left: BinaryTreeNode?
var right: BinaryTreeNode?
init {
this.value = value
left = null
right = null
}
}
*/
fun mirror_image(root: BinaryTreeNode?): Unit {
// Write your code here.
}
#include <bits/stdc++.h>
#include <fcntl.h>
#include <unistd.h>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
using namespace std;
class BinaryTreeNode {
public:
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
BinaryTreeNode(int value) {
this->value = value;
this->left = nullptr;
this->right = nullptr;
}
};
void output_int32(int argument) {
cout << argument;
}
void output_BinaryTreeNode_int32(BinaryTreeNode *argument) {
deque<BinaryTreeNode *> current_level_nodes = {argument};
vector<BinaryTreeNode *> nodes_to_print;
deque<int> print_newlines_before_node_indices;
while (!current_level_nodes.empty()) {
deque<BinaryTreeNode *> next_level_nodes;
while (!current_level_nodes.empty()) {
BinaryTreeNode *node = current_level_nodes.front();
current_level_nodes.pop_front();
nodes_to_print.push_back(node);
if (node != nullptr) {
next_level_nodes.push_back(node->left);
next_level_nodes.push_back(node->right);
}
}
current_level_nodes = next_level_nodes;
print_newlines_before_node_indices.push_back(nodes_to_print.size());
}
while (nodes_to_print.size() > 1 && nodes_to_print.back() == nullptr) {
nodes_to_print.pop_back();
}
cout << "[";
if (nodes_to_print.front() == nullptr) {
cout << "null";
} else {
output_int32(nodes_to_print.front()->value);
}
for (int i = 1; i < nodes_to_print.size(); i++) {
if (i == print_newlines_before_node_indices.front()) {
cout << ",\n";
print_newlines_before_node_indices.pop_front();
} else {
cout << ", ";
}
if (nodes_to_print.at(i) == nullptr) {
cout << "null";
} else {
output_int32(nodes_to_print.at(i)->value);
}
}
cout << "]";
}
int input_int32(json data) {
int argument = data;
return argument;
}
BinaryTreeNode *input_BinaryTreeNode_int32(json data) {
BinaryTreeNode *argument = nullptr; // Root of the tree that we return.
deque<BinaryTreeNode *> nodes_with_uninitialized_children;
bool next_child_is_left = true;
for (auto json_array_item: data) {
BinaryTreeNode *new_node = nullptr;
if (!json_array_item.is_null()) {
new_node = new BinaryTreeNode(input_int32(json_array_item));
if (argument == nullptr) {
argument = new_node;
}
}
if (!nodes_with_uninitialized_children.empty()) {
BinaryTreeNode *parent_node = nodes_with_uninitialized_children.front();
nodes_with_uninitialized_children.pop_front();
if (next_child_is_left) {
parent_node->left = new_node;
} else {
parent_node->right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node != nullptr) {
nodes_with_uninitialized_children.push_back(new_node);
nodes_with_uninitialized_children.push_back(new_node);
}
}
return argument;
}
int main() {
BinaryTreeNode *root;
try {
string json_string = "";
string line;
while (getline(cin, line)) {
json_string+=line;
}
auto data = json::parse(json_string);
root = input_BinaryTreeNode_int32(data["root"]);
} catch(exception &ex) {
cerr << "reading-input-failed-json" << endl;
cerr << ex.what() << endl;
throw ex;
}
dup2(1, 3);
dup2(2, 1);
mirror_image(root);
BinaryTreeNode *result = root;
fflush(stdout);
dup2(3, 1);
if (result) {
vector<BinaryTreeNode *> remaining_nodes;
remaining_nodes.push_back(result);
int number_of_nodes = 0;
while (!remaining_nodes.empty()) {
number_of_nodes++;
if (number_of_nodes > 2000000) {
break;
}
BinaryTreeNode *node = remaining_nodes.back();
remaining_nodes.pop_back();
if (node->left) {
remaining_nodes.push_back(node->left);
}
if (node->right) {
remaining_nodes.push_back(node->right);
}
}
if (number_of_nodes > 2000000) {
throw runtime_error("-------- You returned a tree with either a cycle or too many nodes --------");
}
}
output_BinaryTreeNode_int32(result);
cout << "\n";
return 0;
}
/*
For your reference:
class BinaryTreeNode {
public:
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
BinaryTreeNode(int value) {
this->value = value;
this->left = nullptr;
this->right = nullptr;
}
};
*/
void mirror_image(BinaryTreeNode *root) {
// Write your code here.
}
#include <assert.h>
#include <ctype.h>
#include <fcntl.h>
#include <limits.h>
#include <math.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <cjson/cJSON.h>
typedef struct BinaryTreeNode BinaryTreeNode ;
struct BinaryTreeNode {
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
int ik_number_of_nodes = 0;
void ik_count_nodes(BinaryTreeNode *node) {
if (node == NULL) {
return;
}
if (ik_number_of_nodes > 2000000) {
return;
}
ik_number_of_nodes++;
ik_count_nodes(node->left);
ik_count_nodes(node->right);
}
void output_int32(int argument) {
printf("%d", argument);
}
void output_BinaryTreeNode_int32(BinaryTreeNode *argument) {
BinaryTreeNode **current_level_nodes = malloc(ik_number_of_nodes * 3 * sizeof(BinaryTreeNode *));
int current_level_nodes_first = 0;
int current_level_nodes_last = 0;
current_level_nodes[current_level_nodes_last++] = argument;
BinaryTreeNode **nodes_to_print = malloc(ik_number_of_nodes * 3 * sizeof(BinaryTreeNode *));
int nodes_to_print_first = 0;
int nodes_to_print_last = 0;
int *print_newlines_before_node_indices = malloc(ik_number_of_nodes * 3 * sizeof(int));
int print_newlines_before_node_indices_first = 0;
int print_newlines_before_node_indices_last = 0;
while (current_level_nodes_last > current_level_nodes_first) {
BinaryTreeNode **next_level_nodes = malloc(ik_number_of_nodes * 3 * sizeof(BinaryTreeNode *));
int next_level_nodes_first = 0;
int next_level_nodes_last = 0;
while (current_level_nodes_last > current_level_nodes_first) {
BinaryTreeNode *node = current_level_nodes[current_level_nodes_first++];
nodes_to_print[nodes_to_print_last++] = node;
if (node != NULL) {
next_level_nodes[next_level_nodes_last++] = node->left;
next_level_nodes[next_level_nodes_last++] = node->right;
}
}
free(current_level_nodes);
current_level_nodes = next_level_nodes;
current_level_nodes_first = next_level_nodes_first;
current_level_nodes_last = next_level_nodes_last;
print_newlines_before_node_indices[print_newlines_before_node_indices_last++] = nodes_to_print_last - nodes_to_print_first;
}
free(current_level_nodes);
while (((nodes_to_print_last - nodes_to_print_first) > 1) && (nodes_to_print[nodes_to_print_last - 1] == NULL)) {
nodes_to_print_last--;
}
printf("[");
if (nodes_to_print[nodes_to_print_first] == NULL) {
printf("null");
} else {
output_int32(nodes_to_print[nodes_to_print_first]->value);
}
for (int i = nodes_to_print_first + 1; i < nodes_to_print_last; i++) {
if (i == print_newlines_before_node_indices[print_newlines_before_node_indices_first]) {
printf(",\n");
print_newlines_before_node_indices_first++;
} else {
printf(", ");
}
if (nodes_to_print[i] == NULL) {
printf("null");
} else {
output_int32(nodes_to_print[i]->value);
}
}
printf("]");
free(nodes_to_print);
free(print_newlines_before_node_indices);
}
int input_int32(cJSON *data) {
int argument = data->valueint;
return argument;
}
BinaryTreeNode *input_BinaryTreeNode_int32(cJSON *data) {
BinaryTreeNode *argument = NULL; // Root of the tree that we return.
// cJSON_Array: \`child\` points to a linked list of cJSON items that represent values.
cJSON *json_array_item = data->child; // First item in the array.
int n = 0;
while (json_array_item != NULL) {
n++;
json_array_item = json_array_item->next;
}
BinaryTreeNode **nodes_with_uninitialized_children = malloc(n * 3 * sizeof(BinaryTreeNode *));
int nodes_with_uninitialized_children_first = 0;
int nodes_with_uninitialized_children_last = 0;
bool next_child_is_left = true;
json_array_item = data->child; // Back to the first item in the array.
while (json_array_item != NULL) {
BinaryTreeNode *new_node = NULL;
if (!cJSON_IsNull(json_array_item)) {
new_node = malloc(sizeof(BinaryTreeNode));
new_node->value = input_int32(json_array_item);
new_node->left = NULL;
new_node->right = NULL;
if (argument == NULL) {
argument = new_node;
}
}
if (nodes_with_uninitialized_children_last > nodes_with_uninitialized_children_first) {
BinaryTreeNode *parent_node = nodes_with_uninitialized_children[nodes_with_uninitialized_children_first++];
if (next_child_is_left) {
parent_node->left = new_node;
} else {
parent_node->right = new_node;
}
next_child_is_left = !next_child_is_left;
}
if (new_node != NULL) {
nodes_with_uninitialized_children[nodes_with_uninitialized_children_last++] = new_node;
nodes_with_uninitialized_children[nodes_with_uninitialized_children_last++] = new_node;
}
json_array_item = json_array_item->next;
}
free(nodes_with_uninitialized_children);
return argument;
}
int main() {
BinaryTreeNode *root;
size_t alloc_length = 1024;
size_t cursor = 0;
signed char *json_string = (signed char *) malloc(alloc_length);
signed char ch;
while ((ch = getchar()) != EOF) {
if (cursor >= alloc_length - 1) {
alloc_length <<= 1;
json_string = realloc(json_string, alloc_length);
}
json_string[cursor++] = ch;
}
json_string[cursor] = '\0';
cursor++;
json_string = realloc(json_string, cursor);
cJSON *data = cJSON_Parse(json_string);
root = input_BinaryTreeNode_int32(cJSON_GetObjectItemCaseSensitive(data, "root"));
dup2(1, 3);
dup2(2, 1);
mirror_image(root);
BinaryTreeNode *result = root;
fflush(stdout);
dup2(3, 1);
ik_count_nodes(result);
if (ik_number_of_nodes > 2000000) {
fprintf(stderr, "-------- You returned a tree with either a cycle or too many nodes --------\n");
return 9;
}
output_BinaryTreeNode_int32(result);
printf("\n");
return 0;
}
/*
For your reference:
typedef struct BinaryTreeNode BinaryTreeNode ;
struct BinaryTreeNode {
int value;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
*/
void mirror_image(BinaryTreeNode *root) {
// Write your code here.
}
Attend our free webinar to amp up your career and get the salary you deserve.