简体   繁体   English

比较二叉树的节点

[英]compare nodes of a binary tree

If I have two binary trees, how would I check if the elements in all the nodes are equal.如果我有两棵二叉树,我将如何检查所有节点中的元素是否相等。

Any ideas on how to solve this problem?关于如何解决这个问题的任何想法?

You would do a parallel tree traversal - choose your order (pre-order, post-order, in-order).您将进行并行树遍历 - 选择您的订单(预购、后购、有序)。 If at any time the values stored in the current nodes differ, so do the two trees.如果在任何时候存储在当前节点中的值不同,那么两棵树也是如此。 If one left node is null and the other isn't, the trees are different;如果一个左节点为空而另一个不是,则树是不同的; ditto for right nodes.同样适用于正确的节点。

Does node order matters?节点顺序重要吗? I'm assuming for this answer that the two following trees :对于这个答案,我假设以下两棵树:

  1       1
 / \     / \
3   2   2   3

are not equal, because node position and order is taken into account for the comparison.不相等,因为比较时考虑了节点位置和顺序。

A few hints一些提示

  • Do you agree that two empty trees are equal?你同意两棵空树相等吗?
  • Do you agree that two trees that only have a root node, with identical node values, are equal?您是否同意只有一个根节点且节点值相同的两棵树是相等的?
  • Can't you generalize this approach?你不能概括这种方法吗?

Being a bit more precise更精确一点

Consider this generic tree:考虑这个通用树:

       rootnode(value=V)
           /      \
          /        \
      --------    ------- 
     |  left  |  | right |
     | subtree|  |subtree|
      --------    -------

rootnode is a single node. rootnode是单个节点。 The two children are more generic, and represent binary trees.这两个孩子更通用,代表二叉树。 The children can either be empty, or a single node, or a fully-grown binary tree.子节点可以是空的,也可以是单个节点,也可以是成熟的二叉树。

Do you agree that this representation is generic enough to represent any kind of non-empty binary tree?您是否同意这种表示足够通用以表示任何类型的非空二叉树? Are you able to decompose, say, this simple tree into my representation?你能把这个简单的树分解成我的表示吗?

If you understand this concept, then this decomposition can help you to solve the problem.如果你理解了这个概念,那么这个分解可以帮助你解决问题。 If you do understand the concept, but can't go any further with the algorithm, please comment here and I'll be a bit more specific :)如果您确实理解了这个概念,但无法进一步了解该算法,请在此处发表评论,我会更具体一点:)

您可以使用Tree Traversal 之类的东西来检查每个值。

Let the two tree pass through same tree traversal logic and match the outputs.让两棵树通过相同的树遍历逻辑并匹配输出。 If even a single node data does not match the trees dont match.如果即使单个节点数据不匹配,树也不匹配。

Or you could just create a simple tree traversal logic and compare the node values at each recursion.或者您可以创建一个简单的树遍历逻辑并在每次递归时比较节点值。

You can use pointers and recursion to check if node is equal, then check subtrees.您可以使用指针和递归来检查节点是否相等,然后检查子树。 The code can be writen as following in Java language.代码可以用Java语言编写如下。

public boolean sameTree(Node root1, Node root2){
//base case :both are empty
if(root1==null && root2==null )
   return true;

if(root1.equals(root2)) {
    //subtrees
    boolean left=sameTree(root1.left,root2.left);
    boolean right=sameTree(root1.right,root2.right);
    return (left && right);
}//end if
else{
    return false;
}//end else

}//end sameTree() }//结束sameTree()

Writing a C code as a tag mentions in the question.编写 C 代码作为问题中提到的标签。

int is_same(node* T1,node* T2)
{
    if(!T1 && !T2)
    return 1;
    if(!T1 || !T2)
    return 0;

    if(T1->data == T2->data)
    {
        int left = is_same(T1->left,T2->left);
        int right = is_same(T1->right,T2->right);
        return (left && right);
    }
    else
    return 0;
}

Takes care of structure as well as values.兼顾结构和价值观。

One line code is enough to check if two binary tree node are equal (same value and same structure) or not.一行代码足以检查两个二叉树节点是否相等(相同的值和相同的结构)。

bool isEqual(BinaryTreeNode *a, BinaryTreeNode *b)  
{  
    return (a && b) ?  (a->m_nValue==b->m_nValue && isEqual(a->m_pLeft,b->m_pLeft) && isEqual(a->m_pRight,b->m_pRight)) :  (a == b);  
}

If the trees are binary search trees, so that a pre-order walk will produce a reliable, repeatable ordering of items, the existing answers will work.如果树是二叉搜索树,那么前序遍历将产生可靠的、可重复的项目排序,则现有答案将起作用。 If they're arbitrary binary trees, you have a much more interesting problem, and should look into hash tables .如果它们是任意二叉树,那么您将遇到一个更有趣的问题,并且应该查看哈希表

My solution would be to flatten the two trees into 2 arrays (using level order), and then iterate through each item and compare.我的解决方案是将两棵树展平为 2 个数组(使用级别顺序),然​​后遍历每个项目并进行比较。 You know both arrays are the same order.您知道两个数组的顺序相同。 You can do simple pre-checks such as if the array sizes differ then the two trees aren't the same.您可以进行简单的预检查,例如如果数组大小不同,那么两棵树就不一样。

Level Order is fairly easy to implement, the Wikipedia article on tree traversal basically gives you everything you need, including code.级别顺序相当容易实现,关于树遍历的 Wikipedia 文章基本上为您提供了所需的一切,包括代码。 If efficiency is being asked for in the question, then a non-recursive solution is best, and done using a FIFO list (a Queue in C# parlance - I'm not a C programmer).如果问题中要求效率,那么最好使用非递归解决方案,并使用 FIFO 列表(C# 用语中的队列 - 我不是 C 程序员)来完成。

If your values are numerical int, in a known range, you can use an array, (let's say max value n ).如果您的值是整数 int,在已知范围内,您可以使用数组(假设最大值n )。 Traverse through the 1st tree using whatever method you want, adding the data into a said array, in an appropriate index (using the node data as index).使用您想要的任何方法遍历第一棵树,将数据添加到所述数组中,在适当的索引中(使用节点数据作为索引)。 Then, traverse through the second tree and check for every node in it, if array[node.data] is not null.然后,遍历第二棵树并检查其中的每个节点,如果array[node.data]不为空。 If not - trees are identical.如果不是 - 树是相同的。 **assuming for each tree all nodes are unique **假设每棵树的所有节点都是唯一的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM