r/learnprogramming • • Apr 05 '22

Name one programming/comp sci concept you never understood and if you understand it, try to explain it to them

Name a programming concept such as virtual functions, pointers, certain algorithms, etc that you always had a hard time understanding and why.

Someone else who reads yours and does understand it, try to explain it to them to help them learn

1.6k Upvotes

738 comments sorted by

View all comments

Show parent comments

3

u/0xonox0 Apr 05 '22

Tree balancing is supposed to make tree operations (such as searching, inserting, or deleting) truly O(log(n)). You could have unbalanced trees (think just a linear tree where each node only has a left child) where the tree operations will just morph into a O(n) operation. If we balance the tree the height of the tree will decrease and since tree operations depend on the height, they will also be more efficient on balanced trees. There are various algorithms to make a tree balanced such as AVL trees to red black trees to multiway search trees; imo it's just better to watch a video on this than my trying to explain it to you in a reddit comment but the main goal of this algorithm is to make trees more balanced.

TLDR: Balanced trees lead to more efficient tree operations

1

u/LavenderDay3544 Apr 05 '22

It's the algorithms that elude me. I can write a hash table in assembly but can't wrap my head around algorithmically figuring out when a tree is unbalanced and how to balance it from there.

1

u/ExtraFig6 Apr 06 '22

I think AVL trees are the clearest here because you store the height of the subtrees. So you make sure the left and right's lengths must be close together. If not, you rotate.

1

u/LavenderDay3544 Apr 06 '22

Is the entire algorithm applied recursively?

2

u/ExtraFig6 Apr 06 '22

Yes. You insert the node at the leaf. Then fixup the parent. Then fixup the grandparent. Then the great grandparent etc.

B trees are also not too bad, and are interesting because they can have high branching factors and good cache locality.

The other famous balanced binary tree is the red black tree but the rebalancing algorithm has more cases (4 or 8 depending on the implementation) so it's harder to learn and remember imo.

1

u/LavenderDay3544 Apr 06 '22

B trees are also not too bad, and are interesting because they can have high branching factors and good cache locality.

How does that work? I thought cache locality worked best with contiguous data structures like arrays, vectors, matrices, etc.

2

u/ExtraFig6 Apr 06 '22

It does. But if you need nodes, the next best thing is to put as much data as you can contiguously in the node.

2

u/LavenderDay3544 Apr 06 '22

I see, that makes sense.