Check if two trees are Mirror | Set 2
Given two Binary Trees, returns true if two trees are mirror of each other, else false.
Mirror Tree :
Previously discussed approach is here.
Approach: Find the inorder traversal of both the Binary Trees, and check whether one traversal is reverse of another or not. If they are reverse of each other then the trees are mirror of each other, else not.
Implementation
C++
Java
Python3
C#
Javascript
<script>
class Node
{
constructor()
{
this .data = 0;
this .left = null ;
this .right = null ;
}
};
function inorder(n, v)
{
if (n.left != null )
inorder(n.left, v);
v.push(n.data);
if (n.right != null )
inorder(n.right, v);
}
function areMirror(a, b)
{
if (a == null && b == null )
return true ;
if (a == null || b == null )
return false ;
var v1 = [];
var v2 = [];
inorder(a, v1);
inorder(b, v2);
if (v1.length != v2.length)
return false ;
for ( var i = 0, j = v2.length - 1; j >= 0;
i++, j--)
if (v1[i] != v2[j])
return false ;
return true ;
}
function newNode(data)
{
var node = new Node();
node.data = data;
node.left = node.right = null ;
return (node);
}
var a = newNode(1);
var b = newNode(1);
a.left = newNode(2);
a.right = newNode(3);
a.left.left = newNode(4);
a.left.right = newNode(5);
b.left = newNode(3);
b.right = newNode(2);
b.right.left = newNode(5);
b.right.right = newNode(4);
if (areMirror(a, b))
{
document.write( "Yes" );
}
else
{
document.write( "No" );
}
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Last Updated :
08 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...