zoukankan      html  css  js  c++  java
  • 【IT笔试面试题整理】判断一个树是否是另一个的子树

    【试题描述】定义一个函数,输入判断一个树是否是另一个对的子树

    You have two very large binary trees: T1, with millions of nodes, and T2, with hun-dreds of nodes Create an algorithm to decide if T2 is a subtree of T1

    Note that the problem here specifies that T1 has millions of nodes—this means that we should be careful of how much space we use Let’s say, for example, T1 has 10 million nodes—this means that the data alone is about 40 mb We could create a string representing the inorder and preorder traversals If T2’s preorder traversal is a substring of T1’s preorder traversal, and T2’s inorder traversal is a substring of T1’s inorder traversal, then T2 is a sub-string of T1 We can check this using a suffix tree However, we may hit memory limitations because suffix trees are extremely memory intensive If this become an issue, we can use an alternative approach Alternative Approach: The treeMatch procedure visits each node in the small tree at most once and is called no more than once per node of the large tree Worst case runtime is at most O(n * m), where n and m are the sizes of trees T1 and T2, respectively If k is the number of occurrences of T2’s root in T1, the worst case runtime can be characterized as O(n + k * m)

    【参考代码】

     1 boolean containsTree(Node t1, Node t2)
     2     {
     3         if (t2 == null)
     4             return true;
     5         else
     6             return subTree(t1, t2);
     7     }
     8 
     9     boolean subTree(Node r1, Node r2)
    10     {
    11         if (r1 == null)
    12             return false;
    13         if (r1.value == r2.value)
    14         {
    15             if (matchTree(r1, r2))
    16                 return true;
    17         }
    18         return (subTree(r1.left,r2) || subTree(r1.right,r2));
    19     }
    20 
    21     boolean matchTree(Node r1, Node r2)
    22     {
    23         if (r2 == null && r1 == null)
    24             return true;
    25         if (r1 == null || r2 == null)
    26             return false;
    27         if (r1.value != r2.value)
    28             return false;
    29         return (matchTree(r1.left, r2.left) && matchTree(r1.right, r2.right));
    30     }
  • 相关阅读:
    css3 可穿透的盒子标签属性 pointer-events
    Visual Basic 6.0精简版下载地址
    VB实现七彩过渡渐变色效果
    ExcelVBA联考中学校自动分配
    VB经典的推箱子小游戏源程序
    坦克大战小游戏源程序
    扫雷初级版V1.0源程序
    班级随机点名程序
    VB弹力球源程序
    老师如何听课和评课?4个维度、20个观察视角、68个观察点!
  • 原文地址:https://www.cnblogs.com/WayneZeng/p/9290755.html
Copyright © 2011-2022 走看看