-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_05.java
More file actions
95 lines (81 loc) · 1.95 KB
/
Copy pathBT_Problem_05.java
File metadata and controls
95 lines (81 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package trees.binaryTree;
/* Problem Title :- Find Mirror of a tree.
*
* Mirror of a tree :-
* The Diameter of a tree is the number of nodes on the longest path
* between two end nodes.
*/
class Node {
int data;
Node root, left, right;
public Node(int value) {
data = value;
root = left = right = null;
}
}
public class BT_Problem_05 {
/*
* A binary tree node has data,
* pointer to left child
* & a pointer to right child
*/
static class node {
int val;
node left;
node right;
}
/*
* Helper function that allocates a new node with the given data
* & null left and right pointers
*/
static node createNode(int val) {
node newNode = new node();
newNode.val = val;
newNode.left = null;
newNode.right = null;
return newNode;
}
/*
* Helper function to print
* In-order Traversal
*/
static void inorder(node root) {
if (root == null)
return;
inorder(root.left);
System.out.println(root.val);
inorder(root.right);
}
/*
* mirror-i-f-y function takes two trees,
* original tree and a mirror tree
* It recurses on both the trees.
* but when original tree recurses on left,
* mirror tree recurses on right and vice-versa
*/
static node mirrorify(node root) {
if (root == null)
return null;
// Create new mirror node from original tree node
node mirror = createNode(root.val);
mirror.right = mirrorify(root.left);
mirror.left = mirrorify(root.right);
return mirror;
}
// Driver Code
public static void main(String[] args) {
node tree = createNode(5);
tree.left = createNode(5);
tree.right = createNode(5);
tree.left.right = createNode(5);
tree.left.left = createNode(5);
// print in-order traversal of the original input tree
System.out.print("\n Inorderr of original tree: ");
inorder(tree);
node mirror = null;
mirror = mirrorify(tree);
// print in-order traversal of the mirror tree
System.out.print("\n Inorderr of mirror tree: ");
inorder(mirror);
}
}