简体   繁体   中英

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. 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.

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()

Writing a C code as a tag mentions in the question.

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. 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. 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).

If your values are numerical int, in a known range, you can use an array, (let's say max value 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. If not - trees are identical. **assuming for each tree all nodes are unique

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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