Binary Trees question. Checking for similar shape

后端 未结 5 606
刺人心
刺人心 2021-01-06 06:49

Hi I\'m stuck doing this, not sure how to go about it.

If I have two binary trees, how would I check if the have the same shape? Data in the nodes doesn\'t matter, j

5条回答
  •  天命终不由人
    2021-01-06 07:36

    Just follow the branches, mimicking each move in one tree in the other. In Python pseudo-code:

    class Tree:
        def __init__(self, value, left=None, right=None):
            self.value = value
            self.left = left
            self.right = right
    
    def same_shape(T1, T2):
        if T1 == None:
            return T2 == None
    
        if T2 == None:
            return T1 == None
    
        return same_shape(T1.left, T2.left) and same_shape(T1.right, T2.right)
    

提交回复
热议问题