Lesson 2 - Common Data Structures in Python

What is the code for preorder and postorder traversal of a binary tree?

Basically:

Preorder

  1. Print
  2. Visit left subtree (if available)
  3. Visit right subtree (if available)

Postorder

  1. Visit left subtree (if available)
  2. Visit right subtree (if available)
  3. Print
1 Like

Hey, of-topic but how did you get that not equals sign in python.
And also, does it work the same way as != or is it different?

image ]
can someone explain self.users.insert(i,user) work

1 Like

self.users is calling the UserDatabase() object attribute ‘.users’. If you look further up in the constructor (def init(self) ), it is defined as a list.

So in order to insert an item (ex. user) into the list, you can use the insert() method, which is a standard python method for lists. It takes 2 arguments:

  1. position where to insert the item (ex. at position i)
  2. item to insert into the list (ex. in this case, we are inserting variable ‘user’)

So in this case, you are iterating through the existing list of users (while loop) until the condition is met where the username in the list > username of the new user you are trying to insert (user.username). This gives us the right position (i) to insert the user into the list.

2 Likes

Can anyone solve the leetcode question to check completeness of a binary tree

check this chapter and i’m unable to display the tree for all tuples

Why do we use the former way?

The class method invocations TreeNode.height(node) and node.height() are equivalent. Can you guess why we’re using the former in the function definitions above? Hint: Track the recursive calls.

thanks for sharing this. it is really helpful. but i do have a question. why are they are not explaining we are using standard library of python in this case because we have the same name method in the class. it is difficult to find out which one we are using.