Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

please write in JAVA ! Java class TreeNode is defined as below. 1 2. 3 4 5 public class TreeNode { public int val; public

please write in JAVA !

image text in transcribed

image text in transcribed

image text in transcribed

Java class TreeNode is defined as below. 1 2. 3 4 5 public class TreeNode { public int val; public TreeNode left, right; public TreeNode(int x) { val = x; } public TreeNode(int x, TreeNode leftChild, TreeNode rightChild) { val = x; left = left = leftChild; right = rightChild; } } In this question, please write a recursive method that constructs a string consists of parenthesis and integers from a binary tree with the preorder traversing way. The null node needs to be represented by empty parenthesis pair "()". What is more, you need to omit all the empty parenthesis pairs that do not affect the one-to-one mapping relationship between the string and the original binary tree. 1) You only have the reference to the root node in the input binary tree. 2) Your method must be recursive. You will receive zero credit for this question if your method is not recursive, no matter it is correct or not. 3) Your algorithm should have time complexity of O(n), where n is the size (number of nodes) of the input binary tree. 4) You do not need a wrapper method in this question. 5) Please only complete the required method. Do not write a maint) program or any testing code! Example 1 Method Argument 2 3 4 Expected Method Return value "1(2(4))(3)" Explanation Originally it needs to be "1(204)())(30) 0)", but you need to omit all the unnecessary empty parenthesis pairs. Then, it becomes "1(2(4))(3)". Example 2 Method Argument 3 4 Expected Method Return Value "1(2() (4))(3)" This example is almost the same as the first example. However, we cannot omit the first parenthesis pair to break the one-to- one mapping relationship between the input and the output. The first empty pair of parentheses indicates that the left child of "2" is null Explanation

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions