Preorder Traversal in a Binary Tree (With C Code)

CodeWithHarry
12 Dec 202011:24

Summary

TLDRIn this video, the speaker provides an in-depth explanation of preorder traversal in binary trees. Starting with a basic introduction to tree traversals, the speaker explains how preorder traversal works by visiting the root node first, followed by the left subtree, and then the right subtree. Using a sample tree, the process is demonstrated step by step. Additionally, a recursive function for preorder traversal in C programming is explained. The speaker highlights how recursion simplifies traversal tasks and concludes with a demonstration of the code in action, emphasizing its simplicity.

Takeaways

  • 🌳 Preorder traversal is a method for traversing a tree data structure.
  • 📝 The mnemonic for remembering the order of traversal is 'Left-Right-Root' for preorder.
  • 🔑 The key steps in preorder traversal are: visit the root node first, then the left subtree, and finally the right subtree.
  • 👨‍🏫 The video uses a visual example of a tree to demonstrate how preorder traversal is performed.
  • 📑 The script explains a technique to remember the order of traversal by writing 'Root', 'Left', and 'Right' in their respective order.
  • 💡 The script emphasizes the importance of understanding the difference between preorder, inorder, and postorder traversals.
  • 🛠️ Recursion is used in the code to implement the preorder traversal function, simplifying the process.
  • 💻 The script provides a pseudo code example for the preorder traversal function, highlighting the simplicity of the approach.
  • 🔍 Preorder traversal can be used for searching or processing all nodes in a tree, as it visits every node.
  • 📈 The video script includes a step-by-step guide on how to code the preorder traversal function in a programming language.

Q & A

  • What is preorder traversal in a binary tree?

    -Preorder traversal is a tree traversal method where the root node is visited first, followed by the left subtree and then the right subtree. The sequence is Root, Left, Right.

  • How can you remember the order of preorder traversal?

    -A simple way to remember the order is to write the word 'Root' first, followed by 'Left' and 'Right'. This reminds you that in preorder traversal, you visit the root node first, then the left subtree, and finally the right subtree.

  • What would the preorder traversal be for the tree given in the script?

    -The preorder traversal for the given tree is 4, 1, 5, 2, 6.

  • What happens if the root node is NULL in the traversal function?

    -If the root node is NULL, it means that either the tree is empty or you have reached a leaf node. In this case, the traversal function does nothing and simply returns.

  • Why is recursion commonly used for preorder traversal?

    -Recursion is used because the preorder traversal problem is naturally recursive. For each node, you visit the root, then recursively visit the left subtree, and finally the right subtree. Recursion simplifies the implementation of this process.

  • How is the 'preorder' function implemented in code?

    -The 'preorder' function checks if the root is NULL. If it is not, the function prints the root's data and then recursively calls itself for the left and right children of the root.

  • What is the structure of a tree node as mentioned in the script?

    -A tree node is represented as a 'struct node', which contains data and pointers to the left and right child nodes.

  • What are the basic elements inside a tree node?

    -Each tree node contains three elements: data (the value stored in the node), a left pointer (to the left child), and a right pointer (to the right child).

  • How is the preorder traversal output presented in the script?

    -The preorder traversal output is presented as '4, 1, 5, 2, 6'. The presenter humorously refers to this sequence as the 'phone number' of the tree.

  • Why is it important to understand tree traversal in data structures?

    -Tree traversal is crucial in data structures because it allows you to visit every node in a structured manner, which is essential for tasks like searching, inserting, or performing operations on each node.

Outlines

00:00

🌳 Understanding Preorder Traversal in Trees

In this section, the speaker introduces the concept of preorder traversal in trees, building on previous discussions about tree traversals. They explain how to perform preorder traversal by visiting the root node first, followed by the left and right subtrees. The speaker emphasizes the importance of remembering traversal orders by using mnemonics and guides the audience through an example tree. They explain how to mark subtrees and recursively apply preorder traversal to different parts of the tree.

05:00

💻 Writing the Preorder Traversal Function

This paragraph delves into the coding part of preorder traversal. The speaker walks through writing a simple C function to implement the traversal. They describe the structure of the `struct node` used to represent a tree node, explain the base case for the recursive function (when the root is null), and outline the process for printing the root node’s data. The speaker points out that recursive calls are made to traverse the left and right children, using pseudo code and addressing potential coding mistakes, such as missing semicolons, when transitioning to an actual code editor.

10:01

🚀 Running the Preorder Traversal Code

The final paragraph covers testing the preorder traversal function. The speaker runs the function on a predefined tree (4, 1, 6, 5, 2) and verifies the output matches the expected preorder sequence (4, 1, 5, 2, 6). They emphasize the simplicity and effectiveness of recursion in solving traversal problems. The section concludes with a reminder for viewers to follow the complete Data Structures and Algorithms playlist, especially for those who may have missed earlier videos.

Mindmap

Keywords

💡Preorder Traversal

Preorder traversal is a tree traversal method where the root node is visited first, followed by the left subtree, and then the right subtree. In the video, it is explained as 'Root, Left, Right,' and the presenter shows how this order is applied in practice using an example tree with the nodes 4, 1, 5, 2, and 6.

💡Root Node

The root node is the topmost node in a tree data structure, from which all other nodes descend. In the context of the video, the root node is the first node to be visited during preorder traversal. For the example tree, node 4 is the root.

💡Subtree

A subtree is a portion of a tree that includes a node and all of its descendants. In the video, the presenter refers to 'subtree 1' and 'subtree 2' to break down the preorder traversal process and shows how each subtree is visited in turn.

💡Tree Traversal

Tree traversal refers to the process of visiting all the nodes in a tree data structure in a specific order. The video covers one such method, preorder traversal, but also briefly mentions other traversal methods like inorder and postorder, each with a different node visitation order.

💡Recursive Function

A recursive function is a function that calls itself to solve a problem by breaking it down into smaller instances. In the video, the preorder traversal function is implemented recursively, allowing the function to call itself on the left and right subtrees of the current root node.

💡Data Structure

A data structure is a way of organizing and storing data to enable efficient access and modification. The video focuses on the tree data structure, demonstrating how tree traversal can be used to visit all nodes. Specifically, it shows how preorder traversal is performed on a binary tree.

💡Struct Node

A struct node in programming is a data structure that holds information, typically including pointers to other nodes (left and right children) and data values. In the video, the presenter explains how a struct node is defined in the context of a binary tree, containing the node's data and its left and right pointers.

💡Null Check

A null check ensures that a pointer or reference is not pointing to null (i.e., no valid data) before accessing it. In the video, the preorder traversal function checks if the root is null before proceeding, ensuring that it does not attempt to traverse an empty tree or reach beyond the leaf nodes.

💡Pseudo Code

Pseudo code is a simplified, informal way of writing a program's logic without focusing on syntax specific to any programming language. In the video, the presenter writes pseudo code to explain the logic of preorder traversal, using it as a teaching tool before implementing the actual code.

💡Binary Tree

A binary tree is a type of tree data structure where each node has at most two children, referred to as the left and right child. The video presents an example of a binary tree with nodes 4, 1, 5, 2, and 6, and walks through how preorder traversal works on this structure.

Highlights

Introduction to preorder traversal, a type of tree traversal method.

Recap of the previous video, which provided an overview of tree traversals and why they are done.

Step-by-step explanation of how to perform preorder traversal on a sample tree.

Reminder: Root, Left, Right is the order in preorder traversal.

Tip to remember different traversals: Write 'Root' for preorder, 'Root' at the end for postorder, and 'Root' in between for inorder.

Starting preorder traversal from the root node of the tree.

Breakdown of the traversal process: visit the root first, then the left subtree, followed by the right subtree.

Illustration of how to solve a subtree and mark nodes during the traversal process.

Practical example: The preorder traversal result for a tree with nodes 4, 1, 5, 2, 6.

Explanation of a recursive function to perform preorder traversal in code.

Introduction to struct node in C, used to represent tree nodes.

Pseudo-code demonstration for preorder traversal with basic conditional logic.

Clarification of the use of recursion to simplify tree traversal problems.

Coding example of preorder traversal: showing how to print nodes in the correct order.

Conclusion: Encouragement to review the playlist for a comprehensive understanding of Data Structures and Algorithms.

Transcripts

play00:00

In today's video

play00:01

we are going to look at the preorder traversal thoroughly.

play00:03

In the last video, I had given you a very good idea of ​​traversals

play00:07

That why these tree traversals are done.

play00:09

And today we'll take a closer look at the preorder traversal

play00:13

And this tree which I have just made for you people

play00:16

I will show you as an example

play00:18

that how to do preorder traversal

play00:20

So, the tree you see, we are going to do preorder traversal in it

play00:24

So, what is preorder traversal called, right?

play00:27

I told you people

play00:28

Sometimes you forget that what is pre,

play00:30

what is post,

play00:31

and what is in order

play00:33

So, what should you do

play00:34

First you write

play00:35

You write left in left,

play00:37

write left in left,

play00:38

you write right in right

play00:40

Okay

play00:41

Wrote right on the right side, left written on the left side

play00:43

If it is pre then write the Root here

play00:46

Ok, if there was a post then I would write the Root here

play00:48

And if these were (in)

play00:49

then the Root would be written inside these two,

play00:51

i.e., write (in) here, Ok

play00:52

That's a way of remembering, OK

play00:54

Root, Left or Right this is our preorder traversal

play00:57

That you first visit the root node

play01:00

After that you guys visit the left subtree

play01:04

then visit the right subtree, OK

play01:06

So, there is Root, after that Left and after that Right

play01:10

This is our preorder traversal, Ok

play01:14

So, this is our preorder traversal

play01:15

In this, if I talk about what I will do first

play01:17

I will visit the root, the root node of this tree

play01:20

So, I will visit on 4th, OK, then I will say 4

play01:24

After whom will I visit

play01:26

I will visit the left subtree

play01:27

I will finish this whole

play01:30

And after that I will finish the right subtree

play01:32

Now when I finish it completely

play01:34

That is, this dotted subtree I am making for you guys.

play01:38

I will write it after finishing in full, after 4, after root, Ok

play01:42

And when I visit it then some of its nodes will come

play01:45

I don't know what they will be, Ok

play01:47

I don't want to take that much headache for now

play01:49

I'll say this is my subtree 1, Ok

play01:52

I'll mark it, it's subtree 1

play01:55

And I have to write this sub tree by doing it right now

play01:58

I just let it be

play02:00

After that I make this subtree 2, subtree 2

play02:03

Luckily, we have a little subtree is just one root node

play02:06

So, it's only 6, Ok

play02:08

Because there is only one node

play02:10

Root, Left, Right is happening

play02:11

There is no Left, Right of that 6

play02:13

So here it comes to 6

play02:14

If it was also a big subtree

play02:15

I would have written it here by making brackets

play02:16

I will see this too later, Ok

play02:19

Now here we have subtree 1

play02:20

I should have written 1 here too

play02:21

So that I know for whom I made this bracket

play02:24

I made this bracket for subtree 1

play02:26

So, I'll write it like this, Ok

play02:28

What will I do now

play02:30

Now I will solve this subtree

play02:31

I will solve this subtree 1 which I have created

play02:33

So, what will come first

play02:34

The root node will come, Ok

play02:36

I write 1 here

play02:38

What will come after that

play02:39

After that left

play02:40

There is only one node in the left

play02:42

So, I will directly write it as 5 and 2, Ok

play02:46

And here it is our preorder traversal

play02:49

4,

play02:50

1,

play02:51

5,

play02:52

2,

play02:52

6

play02:54

So, this is our preorder traversal

play02:57

for this particular tree, Ok

play02:59

4, 1, 5, 2, 6

play03:01

Okay

play03:01

4, 1, 2, 5, 6 is the phone number of this tree

play03:04

What is the phone number

play03:05

Preorder

play03:06

phone number means traversal

play03:07

Ok, understand something like this

play03:08

So, this is 4, 1, 2, 5, 6 this is our

play03:12

preorder traversal of this tree

play03:14

I hope everyone got it, Ok

play03:17

Now how to code this

play03:18

If I have been given a tree

play03:20

Let's say I have made a tree man

play03:21

Like we saw in our previous videos.

play03:24

That we had made the tree

play03:25

We had made all the pointers

play03:27

In some way we had made these pointers here, this way

play03:31

I'll take a black color over here

play03:33

Let's also maintain a little bit of beauty

play03:36

Okay

play03:38

Like this

play03:38

Like this

play03:39

I'll take these pointers, Ok

play03:42

And what is this ours, what is this node

play03:44

This is a struct node, Ok

play03:47

struct node

play03:49

So, this is our struct node

play03:52

I made (d) a bit weird, but okay

play03:54

Ok, this is our struct node

play03:56

What did the struct node look like to us

play03:57

The struct node we saw

play03:58

Inside it was a left, a right

play04:01

and there was a left, right pointers

play04:03

And one was our data

play04:04

Data means whatever is inside our root node

play04:06

Whatever is the value under our node, that's right.

play04:09

So, if I write the function of preorder traversal

play04:11

then how will it look like

play04:12

I'm interested in this thing

play04:14

So, what will I do over here

play04:15

I'll write void here

play04:17

and here I'll write preorder, Ok

play04:19

So, this is our preorder

play04:21

This will be our function

play04:23

and what will I write here

play04:25

I will write

play04:26

struct node * root

play04:32

That is, the root of the tree for which we have to preorder

play04:38

Okay

play04:39

What will i do in this

play04:40

I will say that if the root becomes Null

play04:42

That is, either you come to the leaf node

play04:44

Or you are given a tree whose root is Null

play04:49

We can make such a tree.

play04:50

in which there is nothing inside

play04:51

The whole root is Null for it, Ok

play04:54

Then what will you guys do?

play04:55

Then you guys will not do anything

play04:56

So, if root is not Null then you will do something

play04:59

So, what will you do here

play05:00

You will write

play05:00

if(root != Null)

play05:06

What will you do if your root is not Null?

play05:10

You would say that the first root

play05:12

i.e., which is my data, would like to print it

play05:15

So, first of all I would like to print this

play05:18

So, what will I do here

play05:19

I will write here, printf

play05:22

And here I am writing pseudo code

play05:23

I know that in the pseudo code I write here

play05:27

Sometimes I don't have semicolons

play05:28

I forget to close the double code.

play05:30

I do this just to understand

play05:31

When I come to the VS code and write this thing

play05:33

Then you will understand very well, OK

play05:35

So, some people also used to point out in the comment,

play05:37

That you do not close semicolon, error will come

play05:39

But actually, when I come to the VS code

play05:41

then I take care of all these mistakes.

play05:42

Ok, so what will i do here

play05:43

I will write

play05:45

Print the data of the root

play05:49

And obviously I will write this properly, by (%d)

play05:52

I will write it very well, Ok

play05:54

After that in the next line I will write preorder

play05:56

That is, I will call the same function recursively

play05:59

for which

play06:00

I will call for the left of the root

play06:03

Okay

play06:05

And

play06:07

I'll call preorder for the right of the root

play06:10

right of the root

play06:13

r i g h t

play06:16

Well, when I told you people about the recursion

play06:19

You will remember that I told you people

play06:20

Recursion solves some problems very easily

play06:25

I close the bracket here.

play06:27

The recursion that takes place

play06:28

solves some problems very easily.

play06:31

This is one of those problems

play06:32

This is one of those problems which recursion solves very well.

play06:36

Since the definition of preorder traversal is

play06:38

that what you do first

play06:40

You first print the root node

play06:42

That is, first print the root you have here

play06:44

And after that what you have to do

play06:47

Its left sub tree, its right sub tree, it has to be printed, Ok

play06:50

Root, Left, Right it is called preorder traversal, Ok

play06:54

Now if I paste this function like this

play06:57

then I will get 4, 1, 2, 5, 6 Ok

play06:59

And this is a preorder traversal

play07:01

Well, we used to have a linear data structure,

play07:03

like an array,

play07:04

a linked list

play07:06

In that we had seen that

play07:08

Whenever we use linear data structure

play07:10

we can traverse it either from the beginning to the end,

play07:12

or from the last to the beginning.

play07:16

Why would we want to traverse

play07:18

We would like to visit all the nodes

play07:20

Let us say for adding all the nodes

play07:22

And then let us say for searching all the nodes

play07:25

That is, suppose I am looking for 7 in this tree.

play07:28

No.7

play07:29

So, I am not getting that right now, Ok

play07:31

I went in 4, I went in 1, I went in 6, I am not getting it in 5, 2

play07:34

So, I would like to traverse this in some way

play07:36

4, 1, 5, 2, 6 if I am traversing like this

play07:39

So, what will happen

play07:41

So whatever node is there if it exists then I am finding it in it

play07:46

Okay

play07:48

So, hope you guys have understood what it is, OK

play07:51

Now what we will do here is to code the preorder traversal

play07:55

So, I had already prepared a file here.

play07:58

And what did I do inside it?

play08:00

That I have made up inside that file,

play08:02

4, 1, 6, 5, 2

play08:03

That is, the tree that I showed you a while back.

play08:06

This tree looks like this

play08:08

if I make this tree in front of you people

play08:10

Then it looks something like this

play08:12

4

play08:12

And then I'll write something like this

play08:15

And take 4 a step further

play08:18

So, the tree finally looks like this

play08:20

I made it quickly, 4, 1, 6, 5, 2 for you guys to see

play08:24

That you guys at least know how tree looks, OK

play08:27

So here p, p1, p2, p3, p4, I have made nodes

play08:31

And after creating nodes

play08:32

I have finally made the tree for your convenience.

play08:35

Now we will write the function of preorder traversal, OK

play08:37

The function of preorder traversal which is very simple

play08:40

And

play08:41

It is so easy that I will type it so fast

play08:45

I will type so fast

play08:47

How fast I will type

play08:48

I don't even know how fast I will type

play08:50

Okay

play08:50

So, what will we do now

play08:52

We will give it the struct *

play08:55

and after that we will write the root, Ok, its root

play08:59

We saw what happens in preorder traversal

play09:02

The first thing you have to check in preorder traversal

play09:04

if(root != Null)

play09:10

What will you do if root is not equal to NULL?

play09:12

You guys, here I had to write void preOrder

play09:16

void preOrder

play09:17

because void preorder will not return anything, Ok

play09:19

Preorder is a function which will not return anything

play09:21

Let me capitalize its (O) too,

play09:22

struct node * root, Ok

play09:25

struct node * root

play09:26

That is, the node that I have created that is * root, Ok

play09:29

It's so easy, it's so easy, OK

play09:32

Why is it, why am I saying so much, easy, easy, easy

play09:36

Because actually its easy

play09:37

I will write by (%d) here

play09:39

print the data of the root

play09:42

and at the same time apply a similar function

play09:46

That is, put the preorder

play09:49

In which

play09:50

in the left child of the root

play09:52

and the right child of the root, Ok

play09:55

here in the right

play09:56

And i think this should do, that's about it

play09:58

You say, it's just that easy

play10:00

Yes man, it is so easy

play10:01

What should I do, tell it by making it difficult

play10:03

So, it's very easy, Ok

play10:05

Let's see it by running

play10:06

And

play10:08

run it

play10:10

and game over

play10:12

No game over, we didn't call it, Ok

play10:14

We have to call it

play10:16

If we even call it here, then something will happen.

play10:20

We'll call it here for (p)

play10:22

We will call preorder for (p), then it will call

play10:26

Now game over not must be over

play10:27

4, 1, 5, 2, 6, OK

play10:29

4, 1, 5, 2, 6 only came ours

play10:31

preorder

play10:32

4, 1, 5, 2, 6 OK

play10:34

So, the preorder went very well

play10:35

If you give a space, it will not look a bit good!

play10:38

it would be nice

play10:40

4, 1, 5, 2, 6

play10:41

Okay

play10:42

So, I hope you guys understand what preorder traversal is

play10:46

We have come a long way in Data Structures and Algorithms.

play10:49

If you haven't accessed the playlist, be sure to access it.

play10:52

Because a lot of people watch my videos in between

play10:54

and ask me where it is, where is it

play10:56

It is very important for those people

play10:58

to see the playlist from the beginning

play11:01

That's all in this video for now

play11:03

Thankyou so much guys for watching this video

play11:05

And i will see you

play11:07

Next time.

Rate This

5.0 / 5 (0 votes)

الوسوم ذات الصلة
Tree TraversalPreorderData StructuresCoding TutorialAlgorithmsRecursionProgrammingTree ExamplesC LanguageComputer Science
هل تحتاج إلى تلخيص باللغة الإنجليزية؟