Python Forum

Full Version: Better Tree Height Function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    def height(self):
        left_height = 0
        right_height = 0
        if self.left:
            left_height = self.left.height()
        if self.right:
            right_height = self.right.height()
        return max(left_height, right_height) + 1
How can I clean up my height function? I think it's a bit verbose. I feel like there should be a simpler way to do this?
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
    def height(self):
        try:
            return max([n.height() for n in self.__dict__.values() if isinstance(n, Node)]) + 1
        except ValueError:
            return 1
(Feb-24-2019, 03:56 AM)stullis Wrote: [ -> ]
class Node:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
    def height(self):
        try:
            return max([n.height() for n in self.__dict__.values() if isinstance(n, Node)]) + 1
        except ValueError:
            return 1

Nice and shiny, thank you.