calculating depth of a binary tree in Python

后端 未结 4 1408
春和景丽
春和景丽 2021-02-20 15:16

I am new to programming and am trying to calculate the depth of a binary tree in Python . I believe that my error is because depth is a method of the Node class and not a regula

4条回答
  •  隐瞒了意图╮
    2021-02-20 15:53

    You've got four cases to consider:

    1. Both subtrees are empty.
    2. The left subtree alone is empty.
    3. The right subtree alone is empty.
    4. Neither subtree is empty.

    You've covered cases 1 and 4, but missed 2 and 3. The fix:

    # Return height of tree rooted at this node.
    def depth(self):
        if self.left == None and self.right == None:
            return 1
        elif self.left == None:
            return self.right.depth() + 1
        elif self.right == None:
            return self.left.depth() + 1
        else:
            return max(self.left.depth(), self.right.depth()) + 1
    

提交回复
热议问题