w3resource

Java Exercises: Get a new binary tree with same structure and same value of a given binary tree

Java Basic: Exercise-177 with Solution

Write a Java program to get a new binary tree with same structure and same value of a given binary tree.

Sample Solution:

Java Code:

import java.util.*;

public class Solution {
 public static void main(String[] args) {
  TreeNode t1 = new TreeNode(1);
  TreeNode t2 = new TreeNode(2);
  TreeNode t3 = new TreeNode(3);
  TreeNode t4 = new TreeNode(4);
  TreeNode t5 = new TreeNode(5);
  t1.left = t2;
  t1.right = t3;
  t2.left = t4;
  t2.right = t5;
  System.out.println("Original Treenode:");
  traverseTree(t1);
  System.out.println("\nClone of the said Treenode:");
  TreeNode result = cloneTree(t1);
  traverseTree(result);
 }
 public static TreeNode cloneTree(TreeNode root) {
  if (root == null) {
   return null;
  }
  TreeNode dup = new TreeNode(root.val);
  dup.left = cloneTree(root.left);
  dup.right = cloneTree(root.right);
  return dup;
 }

 private static void traverseTree(TreeNode root) {
  if (root != null) {
   traverseTree(root.left);
   traverseTree(root.right);
   System.out.println(root.val);
  }

 }
}
class TreeNode {
 public int val;
 public TreeNode left, right;

 public TreeNode(int val) {
  this.val = val;
  this.left = this.right = null;
 }
}

Sample Output:

Original Treenode:
4
5
2
3
1

Clone of the said Treenode:
4
5
2
3
1

Flowchart:

Flowchart: Java exercises: Get a new binary tree with same structure and same value of a given binary tree.

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to partition an given array of integers into even number first and odd number second.
Next: Write a Java program to find the longest increasing continuous subsequence in a given array of integers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

Java: Anagrams

Generates all anagrams of a string.

public static List<String> anagrams(String input) {
    if (input.length() <= 2) {
        return input.length() == 2
                ? Arrays.asList(input, input.substring(1) + input.substring(0, 1))
                : Collections.singletonList(input);
    }
    return IntStream.range(0, input.length())
            .mapToObj(i -> new SimpleEntry<>(i, input.substring(i, i + 1)))
            .flatMap(entry ->
                    anagrams(input.substring(0, entry.getKey()) + input.substring(entry.getKey() + 1))
                            .stream()
                            .map(s -> entry.getValue() + s))
            .collect(Collectors.toList());
}

Ref: https://bit.ly/3rvAdAK