• [GeeksForGeeks] Check if two trees are Isomorphic


    Write a function to detect if two trees are isomorphic. Two trees are called isomorphic if one of them can be obtained from other by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic.

    Algorithm

    Two trees are isomorphic in the following 2 cases.

    1. both trees are null;

    2.  a.neither tree is null;

       b.their roots' values are the same;

       c. either tree 1's left subtree is isomorphic with tree 2's left subtree and tree 1's right subtree is isomorphic with tree 2's right subtree;

                or tree 1's left subtree is isomorphic with tree 2's right subtree and tree 1's right subtree is isomorphic with tree 2's left subtree.

    The above algorithm is a natural statement for solving this problem recursively.

     1 public class IsomorphicTree {
     2     public boolean isIsomorphicTree(TreeNode root1, TreeNode root2) {
     3         if(root1 == null && root2 == null) {
     4             return true;
     5         }
     6         else if(root1 == null || root2 == null) {
     7             return false;
     8         }
     9         else if(root1.val != root2.val) {
    10             return false;
    11         }        
    12         return (isIsomorphicTree(root1.left, root2.left) && isIsomorphicTree(root1.right, root2.right))
    13                 || (isIsomorphicTree(root1.left, root2.right) && isIsomorphicTree(root1.right, root2.left));
    14     }
    15 }

    The runtime of this solution is O(m + n), m and n are the number of nodes in tree 1 and 2. 

  • 相关阅读:
    html5中新增的form表单属性
    FORM
    .Net Core 发布失败
    Sql Server查询最近执行sql
    HttpWebRequest.GetResponse()操作超时
    使用SqlBulkCopy批量插入/更新数据
    ADO .NET 往数据库批量插入数据发生错误:超时时间已到,但是尚未从池中获取链接
    Ueditor代码内容前台只显示一行
    Lambda表达式
    委托的简单使用
  • 原文地址:https://www.cnblogs.com/lz87/p/7348684.html
Copyright © 2020-2023  润新知