【问题标题】:Find two Binary Tree are structurally identical发现两个二叉树结构相同
【发布时间】:2014-06-23 14:30:46
【问题描述】:

我最近在面试中被问到

如果两个给定的二叉树在结构上相同但内容不同,那么查找两个给定二叉树的有效算法是什么?

  a 
/   \
b    c
      \ 
       e

  z 
/   \
u    v
      \ 
       t

结构相同。

下一个问题是找出两个二叉树是否在结构上是镜像的?

感谢任何指针或帮助。

我的尝试是

boolean isStrucutrallyIdentitical(BinaryNode root1, BinayNode root2)  {  
   if(root1==null && root2==null) return true;
   if(root1==null || root2==null) return false;
   if(root1!=null && roo2!=null) return true; // instead of value just check if its null or not 
   return isStrucutrallyIdentitical(root1.getLeft(), root2.getLeft()) &&  isStrucutrallyIdentitical(root1.getRight(), root2.getRight()); 
} 

【问题讨论】:

  • 你的尝试在哪里?
  • 嗨,米奇,我已经尝试更新了这个问题。
  • 我不知道有什么特别的 best 方式,但我可能会选择一个遍历顺序(前序、后序或中序)来使用将树转换为表示每个节点有多少个子节点的字符串(例如,在您的示例中为 0211 并按顺序遍历),然后比较字符串。相同的结构将产生相同的字符串。镜像情况有点难,但我怀疑如果你使用中序遍历,在镜像情况下可能会出现一个反转的字符串。
  • @plzdontkillme 实际上你非常接近。首先,您的第二个和第三个ifs 是相同的(请参阅en.wikipedia.org/wiki/De_Morgan%27s_laws)。剩下的 - 试着拿一张纸和笔画一些树,然后尝试手动“执行”你的代码。
  • @twalberg 这太复杂了。

标签: data-structures binary-tree jaas


【解决方案1】:
public boolean areStructuralySame(TreeNode<Integer> tree1, TreeNode<Integer> tree2) {
    if(tree1 == null && tree2 == null) {
        return true;
    }
    if(tree1 == null || tree2 == null) {
        return false;
    } else return (areStructuralySame(tree1.getLeft(), tree2.getLeft()) && areStructuralySame(tree1.getRight(), tree2.getRight()));

}

这很好用

【讨论】:

    【解决方案2】:
    private static boolean compare(TNode curRoot, TNode newRoot) {
        if (curRoot == null && newRoot == null) {
            return true;
        } else if ((curRoot == null && newRoot != null) || (curRoot != null && newRoot == null))
            return false;
        else {
            if (compare(curRoot.left, newRoot.left) && compare(curRoot.right, newRoot.right))
                return true;
            return false;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-01
      • 2011-11-28
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多