Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Binary tree
#2
The median, not the mean. The median is the middle value. There will be close to an equal number of values left and right of the median. The mean doesn't have to be close to the middle at all. The mean of 1, 2, 3, 4, 5, 6, 7, 8, 9, 100000 is 10004.5. The median is 5.

That doesn't really balance the tree though. If the values are sorted end up with a funny shape like this:
Output:
5 / \ 1 6 \ \ 2 7 \ \ 3 8 \ \ 4 9
You could comput the median again for values left and right of the top node. And repeat the process for the next level, and the next level and so on.
root = median(1, 2, 3, 4, 5, 6, 7, 8, 9(
root.left = median(1, 2, 3, 4)
root.right = median(6, 7, 8, 9)
root.left.left = 1
root.left.right = median(3, 4)
root.left.right.right = 4
root.right.left = 6
root.right.right = median(8, 9)
root.right.right.right =
Output:
5 / \ / \ 2 7 / \ / \ 1 3 6 8 \ \ 4 9
What you want to is a way to balance the tree after it is created. This allows adding nodes to the tree after you create it and then re-balancing the tree. It is a challenging problem, but there are lots articles about how to balance a binary tree.
AlexPython likes this post
Reply


Messages In This Thread
Binary tree - by AlexPython - Dec-06-2022, 09:28 PM
RE: Binary tree - by deanhystad - Dec-06-2022, 09:43 PM
RE: Binary tree - by AlexPython - Dec-06-2022, 10:58 PM
RE: Binary tree - by ndc85430 - Dec-07-2022, 06:41 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Python Code for Preorder Traversal of a Binary Tree Bolt 1 671 Sep-22-2023, 09:32 AM
Last Post: Gribouillis
  Python3 binary tree not replacing parent nodes with child nodes Aspect11 0 1,824 Sep-23-2020, 02:22 PM
Last Post: Aspect11
  hex file to binary or pcap to binary baran01 1 5,777 Dec-11-2019, 10:19 PM
Last Post: Larz60+
  Binary tree from a list dan789 14 5,698 Mar-31-2019, 09:08 PM
Last Post: dan789

Forum Jump:

User Panel Messages

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