Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // program to create mirror of a given binary tree recursively
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.util.*;
- import static java.lang.Integer.max;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to return mirror of the binary tree
- static void mirror_tree_recursive(node root){
- if (root == null){
- return;
- }else{
- // creating mirror using postorder traversal
- mirror_tree_recursive(root.left);
- mirror_tree_recursive(root.right);
- node temp = root.left;
- root.left = root.right;
- root.right = temp;
- }
- }
- // function to print the preorder traversal of a binary tree
- public static void preorder(node root) {
- if (root == null) {
- return;
- }
- System.out.print(root.data + " ");
- preorder(root.left);
- preorder(root.right);
- }
- public static void main(String arg[]) {
- node m1 = new node(8);
- m1.left = new node(3);
- m1.right = new node(10);
- m1.left.left = new node(1);
- m1.left.right = new node(6);
- m1.left.right.left = new node(4);
- m1.left.right.right = new node(7);
- m1.right.right = new node(14);
- m1.right.right.left = new node(13);
- node m2 = new node(8);
- m2.right = new node(3);
- m2.left = new node(10);
- m2.left.left = new node(14);
- m2.right.left = new node(6);
- m2.right.right = new node(1);
- m2.left.left.right = new node(13);
- m2.right.left.left = new node(7);
- m2.right.left.right = new node(4);
- System.out.println("Tree #1 before mirroring : ");
- preorder(m1);
- System.out.println("\nTree #1 after mirroring : ");
- mirror_tree_recursive(m1);
- preorder(m1);
- System.out.println("\n\nTree #2 is mirror of Tree #1 to check the correctness : ");
- System.out.println("TREE #1 : ");
- preorder(m1);
- System.out.println("\nTREE #2 : ");
- preorder(m2);
- }
- }
Add Comment
Please, Sign In to add comment