From the course: Python: Recursion

Unlock the full course today

Join today to access over 24,800 courses taught by industry experts.

Traversing a tree using recursion: Python implementation

Traversing a tree using recursion: Python implementation - Python Tutorial

From the course: Python: Recursion

Traversing a tree using recursion: Python implementation

- [Instructor] Okay, so let's code up this binary tree traversal in Python. The first thing we need is a node class which is similar to what we have for the linked list but it now has a left and a right pointed to the next node. So def _init_(self), that's the standard constructor syntax. And we're just going to pass in the data for each node that we create. So self.data equals data and then the left and the right properties are going to be set to none to begin with. So self.left equals a none and self.right also equals none. So each node is basically just a one node tree with no children to begin with. So then, let me just show you what we've got down here on line 29. We've actually built a tree for you, so manually constructed it by simply assigning the left and the right properties starting with a root node of F and for now I'm going to comment out the other traversals apart from the first one, we're going to do…

Contents