Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // 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 convert tree into mirror tree iteratively
- static void mirror_tree(node root){
- // if the node is null then return
- if (root == null){
- return;
- }
- // creating a stack to keep the child pointers
- Stack STACK = new Stack<node>();
- // push root node on the stack
- STACK.push(root);
- while (!STACK.isEmpty()){
- // remove the top node from the stack
- node current = (node)STACK.peek();
- STACK.pop();
- // swap the left and right nodes
- node temp = current.left;
- current.left = current.right;
- current.right = temp;
- // as it is a stack, we push right child node first because we want to access it after operating on the left child
- if (current.right != null){
- STACK.push(current.right);
- }
- if (current.left != null){
- STACK.push(current.left);
- }
- }
- }
- // 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(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