首页 > 代码库 > CC150 4.7

CC150 4.7

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

// It will iterate main tree (millions) nodes.
// Too bad.
boolean isSubTree(Node main, Node sub)
{
  if (main == null)
    return null;
    
  if (main == sub)
    return isTreeEquals(main, sub)
    
  if (main == sub)
    return isTreeEquals(sub, main);
  else
  {
    return isSubTree(main.left, sub) && isSubTree(main.right, sub);
  }
}

boolean isTreeEquals(Node t1, Node t2)
{
  if (t1 == null || t2 == null)
  {
    return t1 == t2;
  }
  else
  {
    return ( t1 == t2 ) && 
      isTreeEquals(t1.left, t2.left) && 
      isTreeEquals(t2.right, t2.right);
  }
}


Any better idea?

CC150 4.7