In: Computer Science
Code using JAVA:
must include a "Main Method" to run on "intelliJ".
Hint: Use recursion
"
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean isSymmetric(TreeNode root) {
}
}
"
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1 / \ 2 2 \ \ 3 3
Follow up: Solve it both recursively and iteratively.
class Node
{
int k;
Node l, r;
Node(int item)
{
k= item;
l = r = null;
}
}
class BinaryTree
{
Node root;
// returns true if trees with roots as root1 and root2 are mirror
boolean isMirror(Node node1, Node node2)
{
// if both trees are empty, then they are mirror image
if (node1 == null && node2 == null)
return true;
if (node1 != null && node2 != null && node1.k == node2.k)
return (isMirror(node1.l, node2.r)
&& isMirror(node1.r, node2.l));
return false;
}
boolean isSymmetric(Node node)
{
// check if tree is mirror of itself
return isMirror(root, root);
}
// Driver program
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.l = new Node(2);
tree.root.r = new Node(2);
tree.root.l.l = new Node(3);
tree.root.l.r = new Node(4);
tree.root.r.l = new Node(4);
tree.root.r.r = new Node(3);
boolean output = tree.isSymmetric(tree.root);
if (output == true)
System.out.println("1");
else
System.out.println("0");
}
}