Pseudocode to compare two trees

后端 未结 5 1979
猫巷女王i
猫巷女王i 2021-02-02 11:11

This is a problem I\'ve encountered a few times, and haven\'t been convinced that I\'ve used the most efficient logic.

As an example, presume I have two trees: one is a

5条回答
  •  -上瘾入骨i
    2021-02-02 11:46

    A simple example code in python.

    class Node(object):
      def __init__(self, val):
        self.val = val
        self.child = {}
    
      def get_left(self):
        #if left is not in the child dictionary that means the element does not have a left child
        if 'left' in self.child:
          return self.child['left']
        else:
          return None
    
      def get_right(self):
        #if right is not in the child dictionary that means the element does not have a rigth child
        if 'right' in self.child:
          return self.child['right']
        else:
          return None
    
    
    def traverse_tree(a):
      if a is not None:
        print 'current_node : %s' % a.val
        if 'left' in a.child:
          traverse_tree(a.child['left'])
    
        if 'right' in a.child:
          traverse_tree(a.child['right'])
    
    
    
    def compare_tree(a, b):
      if (a is not None and b is None) or (a is None and b is not None):
        return 0
      elif a is not None and b is not None:
        print a.val, b.val
        #print 'currently comparing a : %s, b : %s, left : %s, %s , right : %s, %s' % (a.val, b.val, a.child['left'].val, b.child['left'].val, a.child['right'].val, b.child['right'].val)
        if a.val==b.val and compare_tree(a.get_left(), b.get_left()) and compare_tree(a.get_right(), b.get_right()):
          return 1
        else:
          return 0
      else:
        return 1
    
    #Example
    a = Node(1)
    b = Node(0)
    a.child['left'] = Node(2)
    a.child['right'] = Node(3)
    a.child['left'].child['left'] = Node(4)
    a.child['left'].child['right'] = Node(5)
    a.child['right'].child['left'] = Node(6)
    a.child['right'].child['right'] = Node(7)
    b.child['left'] = Node(2)
    b.child['right'] = Node(3)
    b.child['left'].child['left'] = Node(4)
    #b.child['left'].child['right'] = Node(5)
    b.child['right'].child['left'] = Node(6)
    b.child['right'].child['right'] = Node(7)
    if compare_tree(a, b):
      print 'trees are equal'
    else:
      print 'trees are unequal'
    #DFS traversal
    traverse_tree(a)
    

    Also pasted an example that you can run.

提交回复
热议问题