POST 1 of 5 MorningDSAConcept
A tree is a graph without cycles
Trees are everywhere in computer science. File systems. HTML's DOM. Decision trees and random forests in ML. Heaps. Tries. Parser ASTs. JSON's nested objects. Categorisation hierarchies. The formal definition — a connected acyclic graph. Connected means every node is reachable from every other. Acyclic means no loops. From these two properties, you get exactly n-1 edges in any tree of n nodes. (Any more and you'd have a cycle; any fewer and you'd be disconnected.) The vocabulary you'll use: Root — the node we start from. Trees are typically rooted, even though graphs in general aren't. Node — any entry in the tree. Has an optional value, optional children (other nodes), and optionally a parent pointer. Leaf — a node with no children. Internal node — a node with at least one child. Includes the root if the tree has more than one node. Depth — distance from root to a node, measured in edges. Height — depth of the deepest leaf in the subtree. Balanced tree — height stays around O(log n). Insertions and deletions stay fast. Unbalanced tree — height can be O(n). Degenerates to a linked list. Operations slow to O(n). In ML, trees show up most prominently in decision trees and ensembles (random forests, gradient boosting). Each internal node is a split decision (feature X < threshold). Each leaf is a prediction. The tree's depth controls overfitting — too deep memorises training data; too shallow underfits. Most tree problems boil down to 'walk the tree in some order, do something at each node'. The walking algorithm is BFS or DFS (covered next). The 'something' is the problem-specific logic. Learn the traversals. Most tree problems become tractable.
#DSA#Algorithms#Python#100DaysOfCode#CodingInterview#Trees