Trees
Learn about trees and how to build them in Python.
StartKey Concepts
Review core concepts you need to learn to master this subject
Wide and deep trees
Nodes as parents
Trees are composed of nodes
Tree nodes children
Node root
Python TreeNode class
Wide and deep trees
Wide and deep trees
There are two ways to describe the shape of a tree. Trees can be wide, meaning that each node has many children. And trees can be deep, meaning that there are many parent-child connections with few siblings per node. Trees can be both wide and deep at the same time.
Trees: Python
Lesson 1 of 1
- 1Before we start building (planting?) our trees, let’s do a quick inventory of what we’ll need in our Python implementation. We’re going to make the class TreeNodes. TreeNodes: - have a value - hav…
- 2Let’s start by defining our TreeNode class. We’ll begin with having our node store a value, and additional functionality can be layered on in the following exercises.
- 3We have a working TreeNode class, but there’s no time to enjoy a refreshing glass of lemonade. Trees are all about data hierarchy, and we need a parent-child relationship to make that work. To rev…
- 4Let’s explore how to remove nodes from a tree. Remember, child nodes are held in a list within the parent node. To remove a child, we need to remove that node from the list. We want the following …
- 5Trees are an abstract idea that we’re making concrete in Python. When implementing these abstract data structures, it’s important to leverage the features of your language. Let’s refactor .remove…
- 6Our implementation has covered adding and removing nodes. Let’s expand the functionality and add the ability to move through connected nodes. Tree traversal is a standard operation for finding no…
- 7Our implementation of tree traversal has a slight hiccup. Trees grow many levels deep, but we’ve only accounted for one parent-child relationship. How is this a problem? root = TreeNode(‘Founder’…
- 8Congratulations, you have implemented a tree in Python. For review, in our implementation: - Trees are a Python class called TreeNode. - A TreeNode has two properties, value and children. - Nodes …
What you'll create
Portfolio projects that showcase your new skills
How you'll master it
Stress-test your knowledge with quizzes that help commit syntax to memory