How to determine if two binary trees are identical in content?

I see several messages on how to determine if two trees are the same in terms of its structure, but have not found an answer on how to find whether two trees are the same in terms of content.

Let's say a node tree is defined as follows.

TreeNode {
    string data;
    TreeNode* left;
    TreeNode* right
};

Now I have two binary trees and I need to find out if the two trees are the same in content. The two cannot be structurally identical, and we cannot assume that the data row is identical in words.

For example, we can have two trees. These two trees can be considered identical in terms of content when we take a walk. To be clear, when we concatenate all node strings from these two trees, they are the same. i.e. abcdedfg

 (abc)
 |   \
 (d) (efg)

 (a)
 |  \
 (b) (cdefg)

, inorder, , , , , - . , , , , .

.

+4
5

, , . , , , , , , . Python :

def iter_bin_tree_letters(tree):
    if tree.left:
        for letter in iter_bin_tree_letters(tree.left)
            yield letter
    # RETURN ITERATOR OVER LETTERS  <----------
    for letter in tree.data:
        yield letter
    if tree.right:
        for letter in iter_bin_tree_letters(tree.right)
            yield letter

, 2 :

def are_equal_bin_trees(tree1, tree2):
    t1 = iter_bin_tree_letters(tree1)
    t2 = iter_bin_tree_letters(tree2)
    t1_empty = False
    while True:
        try:
            e1 = t1.next()
        except:
            t1_empty = True
        try:
            e2 = t2.next()
        except:
           if not t1_empty:
               return False
           return True
        if e1!=e2:
             return False

, min (n, m) .

+1

, DFS ( ), . , , .

. 1 , Node X-Y - X, Y. 1 Node 2-2 - "efg":

Tree 1
(abc)
 |   \
 (d) (efg)

Tree 2
 (a)
 |  \
 (b) (cdefg)

, .

  • 1 Node 1-1
  • 2 Node 1-1
  • a1 a2
  • 2 Node 2-1
  • b1 b2
  • 2 Node 2-2
  • c1 c2
  • 1 Node 2-1
  • d1 d2
  • 1 Node 2-2
  • e1 e2
  • f1 f2
  • g1 g2
  • !
+1

, , , .

, node , .

 a      a
b c    c d

ab ac . , 1 c 2 b, .

, , pop , , , . , , log(n) node .

0

o (n). ​​ . , .

, , , .

0

- O (n) XOR , XOR , , - O (n) , O (n).

0

Source: https://habr.com/ru/post/1627701/


All Articles