Python Forum
Return size of binary tree
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Return size of binary tree
#2
You could use preorder, and get the len() of the list returned by preorder. If you don't want to build that whole list, you could write a method to just calculate the number of nodes:

def __len__(self):
    if self.is_empty():
        return 0
    else:
        return 1 + len(self.lc()) + len(self.rc())
Note that by naming it __len__, it will be used by the built-in len() function, which is what I do with the calls to the children on line 5.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
Return size of binary tree - by Daniel94 - Jan-05-2020, 12:52 PM
RE: Return size of binary tree - by ichabod801 - Jan-05-2020, 04:09 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Print Binary Tree - Python Daniel94 1 2,803 Jan-08-2020, 09:54 PM
Last Post: ichabod801
  Binary tree for words and simbols OlegBrony 4 5,078 Mar-14-2018, 09:40 AM
Last Post: OlegBrony

Forum Jump:

User Panel Messages

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