Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Better Tree Height Function
#1
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?
Reply
#2
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
Reply
#3
(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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  image.thumbnail(width, height) not working PCesarano 2 3,442 Apr-08-2021, 06:09 PM
Last Post: PCesarano
  Applying row height to all rows including and after row 7 curranjohn46 2 6,592 Oct-14-2019, 03:10 PM
Last Post: curranjohn46
  How to measure an inclined beam width and height in image using python? zyb1003 1 3,236 Nov-07-2017, 05:02 AM
Last Post: heiner55
  Effeciency of passing XML tree object as function arguments sandeepvl 3 5,729 Oct-13-2016, 07:58 AM
Last Post: sandeepvl

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020