Saturday, June 16, 2018

How do you check whether given trees are isomorphic to each other or not?

Problem statement: Given two trees how do we check whether the trees are isomorphic or not !!

Two binary trees root1 & root2 are isomorphic if they are the same structure. The values of nodes does not affect whether two trees are isomorphic or not.  



  1. int IsIsometric(TreeNode root1, TreeRoot root2){
  2. f(root1 == null && root2 == null)
  3. return 1;
  4. if((root1 == null && root2 != null) || (root1 !=null && root2 == null)) return 0;
  5. return (IsIsometric(root1.getLeft(), root2.getLeft()) && IsIsometric(root1.getRight(), root2.getRight()));
  6. }
Time complexity: O(n), Space complexity: O(n)

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...