Тёмный

Find height of a binary tree 

mycodeschool
Подписаться 760 тыс.
Просмотров 565 тыс.
50% 1

See complete series on data structures here:
• Data structures
In this lesson, we have written code to find height of a binary tree using a simple recursion.
For practice problems and more, visit: www.mycodeschool.com
Like us on Facebook: / mycodeschool
Follow us on twitter: / mycodeschool

Опубликовано:

 

16 май 2014

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 220   
@madhav3444
@madhav3444 3 года назад
Can't belive these 6years old videos are so much self explanatory and powerful, thanxx mann, you left ds and algo legacy for us
@Kimoskxt
@Kimoskxt 3 года назад
Factz
@mohdsarim4671
@mohdsarim4671 3 года назад
yupp thats a very well explanation
@bro......
@bro...... Год назад
9 years 😅
@xVermyy
@xVermyy 7 лет назад
Your videos helped me understand in 10 minutes what my data structures professor couldn't help me understand in a semester. Thank you :)
@mayank_upadhyay_19
@mayank_upadhyay_19 4 года назад
Recursion feels like, I am looking in a mirror at myself, who is already looking in his mirror at himself.
@davidlaidbiggestfan212
@davidlaidbiggestfan212 4 года назад
facts
@pokerfaced8139
@pokerfaced8139 4 года назад
i am a simple man when i see recursion, i panic
@samkitjain2136
@samkitjain2136 3 года назад
so true feels like a never ending loop
@usmanGTA
@usmanGTA 3 года назад
Yeah, but each look at yourself slightly differs... With each look, you lose hair. And right before you get to the break case, you die, your life flashes before your eyes as the recursion begins to reverse and return to all of the stacks above it...
@codysiegmann5637
@codysiegmann5637 4 года назад
Awesome explanation of the recursive calls as well as the base case (exit condition) and how changing -1 and 0 in the base case will calculate the height of the tree or the number of nodes in the tree, respectively.
@WebgaraCom
@WebgaraCom 8 лет назад
You are here in data structure. You save us in final exam. Please keep going!
@jm.101
@jm.101 4 года назад
Such a great explanation! Helped me to understand balanced and unbalanced trees!
@sparshbohra4135
@sparshbohra4135 3 года назад
source code for people confused: int height (struct bstnode *root) { if (root == NULL) { return -1; } else { int left = height (root->left); int right = height (root->right); int height = (left < right) ? right+1 : left+1; return height; } }
@abuhurrara9171
@abuhurrara9171 3 года назад
Thanks
@avinashmaurya3625
@avinashmaurya3625 3 года назад
or you can #include in c++ to make max() function work
@gool7947
@gool7947 3 года назад
@@bgmishortmoments No it is correct, it should be -1 only because we know height of leaf node is zero but if we take return 0, then it will give height 1 after adding maximum value with 1 (0+1)so it should be -1 only(-1+1) which will ultimately give the height of leaf node zero.
@siddheshchunale1524
@siddheshchunale1524 3 года назад
aah haa me too used bstnode 🤞
@hatsuharu333
@hatsuharu333 8 лет назад
You explain the concepts really well. Thank you!
@easynow6599
@easynow6599 2 года назад
excellent video! especially the fact that for the base case (return -1) you showed how it will work for a leaf node.. here is the Python code: def height(root): if not root: return -1 heightRight = height(root.right) heightLeft = height(root.left) return max(heightRight, heightLeft) + 1
@lravikiran88
@lravikiran88 8 лет назад
sir your logic on how u use recursion for finding the sum is superb.....
@arnabthakuria2243
@arnabthakuria2243 7 лет назад
You are a great teacher
@yangliu8096
@yangliu8096 8 лет назад
Your video is very enlightening, thank you
@khursheedali8286
@khursheedali8286 8 лет назад
we can also do inorder or any traversal and at each node increment count .... now use the formula ceiling( log(n+1) - 1 ) for finding height ... n- nno of nodes
@saisanthosh4653
@saisanthosh4653 7 лет назад
Very neatly explained. Thank you
@rainaw0924
@rainaw0924 9 лет назад
Thank you for the video and a clear explanation.
@tringuyenucminh167
@tringuyenucminh167 4 года назад
oh god, you are a good teacher. Easy to understand.
@CravinMacNCheese
@CravinMacNCheese 8 лет назад
this helped so much. do you have a video on balancing a binary tree?
@Mr1dent1ty
@Mr1dent1ty 8 лет назад
Really great tutorials!!! Keep it up!!
@vijaykari1809
@vijaykari1809 9 лет назад
As we use in general terms, height - measured from bottom to top(i.e.,)from ground level to how much height it went depth - measured from top to bottom (i.e.,) from ground level to how deep it went..
@arbg2566
@arbg2566 3 года назад
Thanks for this course!
@qR7pK9sJ2t
@qR7pK9sJ2t 5 лет назад
if you know the logic of height and depth.. Directly go to 3:05
@mohammedsadiq1567
@mohammedsadiq1567 4 года назад
Thank you!
@VarunVishwakarma1
@VarunVishwakarma1 3 года назад
Why did u stop making videos? Please continue. You are the one who made DS easy for me.
@vikramsapate8703
@vikramsapate8703 3 года назад
He died in one car accident.
@2222stunner
@2222stunner 6 лет назад
Its worth pointing out that when 'max' is defined as a macro, the tree is traversed in a different order as compared to a function based one. Specifically, in the function based one, a node is visited atmost once. But in macro based one, some nodes are visited many times (verified it by using printf). The results are the same, however. Can someone please explain why it is so?
@letmeregisterbitch
@letmeregisterbitch 7 лет назад
Great lesson! Thanks alot
@siddharthtrikha2051
@siddharthtrikha2051 9 лет назад
Thanks a lot for all your videos :) Keep up the good work.
@chandramohanrai9314
@chandramohanrai9314 9 лет назад
your videos are amazing..... a student can learn starting from 0 to 90% of data structure in just 3-4 days. can u share link for source code of height of b.s.t.
@deeproy7292
@deeproy7292 6 лет назад
very well explained...thank you
@fsl4faisal
@fsl4faisal 8 лет назад
neat explanation..!! Thank you so much..!
@emanuelebosco594
@emanuelebosco594 Год назад
thanks a lot for helping us!
@thuanbuibach7284
@thuanbuibach7284 6 лет назад
Thank you so much, you are great teacher ^^
@AdarshTrivedi720
@AdarshTrivedi720 9 лет назад
Great explaination.................bang on.....
@usama57926
@usama57926 6 лет назад
amazing explanation i think u are a tutor
@kanishknagar2606
@kanishknagar2606 4 года назад
great work dude
@elijaheinstein160
@elijaheinstein160 6 лет назад
Good one ! Thanks !
@elisson357
@elisson357 6 лет назад
Thanks for sharing this.
@nickkosi3222
@nickkosi3222 9 месяцев назад
Thank YOU Very Much for the clarity God bless YOU!!!!!!!!!!!
@kevin-kuei
@kevin-kuei Год назад
Brilliant videos!
@gurramsaikiran9383
@gurramsaikiran9383 7 лет назад
U just nailed it :) :) Thanks
@roushanraj2155
@roushanraj2155 8 лет назад
Rashmi ,you have to store base condition of each recursion of node
@blearchive
@blearchive 9 лет назад
this 's great tutorial
@sr5726
@sr5726 9 лет назад
Amazing Videos! Could you please tell, what software you are using to capture and make these videos?
@arunkumar-ic5rj
@arunkumar-ic5rj 9 лет назад
Very nice explain .Please keep going ....
@mcirami
@mcirami 10 лет назад
Thank you so much for the videos. I've learned a lot from you. One thing I don't understand about this is how the actual value of the height is found? How is it returning a count of left edges and right to determine which is max?
@mycodeschool
@mycodeschool 10 лет назад
Matteo C You need to watch previous videos in this series to understand how recursion works for trees. Find min and max element in a binary search tree
@11m0
@11m0 8 лет назад
+mycodeschool I watched the video and I still don't get it. How does it count the number of nodes or the number of edges in the left and right subtrees? Is this something that happens in the background?
@cph82612
@cph82612 8 лет назад
+11m0 To calculate the height, you only need to find the path to leaf with maximum number of edges. So you make recursive call to go through the tree, and each time the recursive call returns, the value will be incremented by 1. Say when we're on node 5 in the video, it'll first call FindHeight(root -> left), which goes to node 8. Node 8 will again call FindHeight(root -> left). The left child of node 8 is NULL, so it'll return -1. Node 8 then call FindHeight(root -> right). The right child of node 8 is also NULL, so it'll return -1. Now node 8 will return max(left height, right height) + 1. Since both child nodes of node 8 are NULL and return -1 (max(-1,-1) = -1) , it'll return -1 +1 which is 0. It shows the height of node 8 is 0. Now node 5 calls FindHeight(root -> right), which goes to node 9, and like node 8, it'll return 0 because the height of 9 is 0. And then node 5 returns max(left height, right height) + 1, which will be max(0,0) + 1 = 1. When node 5 return height to node 2 with height of 1, node 2 returns again max(left height, right height) + 1, which will be max(0, 1) + 1 = 1+1 = 2 (left height is height of node 4 which is 0), so height of node 2 will be 2. Because each recursive call returns (something) + 1, and the (something) compares the left and the right height, the maximum height can be determined and incremented in each return.
8 лет назад
+Benjamin Hsu thank you ı really understand.
@lravikiran88
@lravikiran88 8 лет назад
superb sir.... u just made the explanations much more clearer...... and we must all appreciate the way our sir in video used recursion to compute the height ... wow talk about arithmetics on recursion ..
@santoshr4212
@santoshr4212 11 месяцев назад
this is awesome sir
@nestorguemez4846
@nestorguemez4846 2 года назад
excellent video!
@mulgamarathikudipunjabi
@mulgamarathikudipunjabi 8 лет назад
Properly Explained !!
@shailjakantupadhyay5183
@shailjakantupadhyay5183 7 лет назад
+mycodeschool I watched the all your previous videos and understood it but specifically this video i don't get. How does it count the number of nodes or the number of edges in the left and right subtrees? i need more explanation of code with any example.
@ashwanivarshney9406
@ashwanivarshney9406 6 лет назад
sir all the videos were very helpful but can you please provide some more videos related to algorithms like red black tree,greedy algorithms graph dfs and bfs and all...
@sarvdeepsangwan1207
@sarvdeepsangwan1207 3 года назад
one of the partners of mycodeschool died in an accident. so other one decided to not post videos anymore :(
@ShivamKendre-fc3su
@ShivamKendre-fc3su 3 года назад
Great videos
@navroze92
@navroze92 9 лет назад
Could you please upload videos in dynamic programming it is one of the most powerful and fundamental concepts in computer science if you could do that it would be of great help as there is no one who teaches computer science concepts like you do:)
@jaekim9496
@jaekim9496 9 лет назад
navroze92 Hey! I don't know if you still want to learn about dynamic memory, but he has a series of videos on it if you want to watch it. They are very very very good.
@navroze92
@navroze92 9 лет назад
Jae Kim Could u please put the link for dynamic programming
@joyawang5952
@joyawang5952 4 года назад
Anyone has the same problem with me? The function only returns the result of FindHeight that goes last in the max function parameters. For example, if I put "return max(FindHeight(root->left), FindHeight(root->right)) + 1;" , it returns the height of right, and if I switch left and right like this, "return max(FindHeight(root->right), FindHeight(root->left)) + 1;" , it returns the height of left.
@gowtham3340
@gowtham3340 6 лет назад
Your voice is perfect. No need subtitles... You just avoid the subtitles , because some of the content not visible
@shivamsaxena5854
@shivamsaxena5854 5 лет назад
you can turn off caption by clicking on the 3 vertical dots showing on the upper right side of your screen
@lynx2244
@lynx2244 4 года назад
Why don't you turn off the captions then? There might be some students who are deaf or audibly impaired!
@sushantagawane8683
@sushantagawane8683 3 года назад
Thanks mann !
@gabrielpereiramendes3463
@gabrielpereiramendes3463 5 лет назад
Very Good!
@VISHALBHANDARE
@VISHALBHANDARE 9 лет назад
int maxDepth(struct node* node) { if (node==NULL) return -1; else { /* compute the depth of each subtree */ int lDepth = maxDepth(node->left); int rDepth = maxDepth(node->right); /* use the larger one */ if (lDepth > rDepth) return(lDepth+1); else return(rDepth+1); } } #functionInC
@monicaslv323
@monicaslv323 8 лет назад
+VISHAL BHANDARE Thank you very much. I am so confused about trees. I dont know how i call its recursive functions from main in ADT.
@gmaniket
@gmaniket 6 месяцев назад
Thank you.
@jinyi0313
@jinyi0313 6 лет назад
how to find possible triangle in binary tree. example if i insert 7 it will return 4 triangle. thank you for answer
@leontube007
@leontube007 3 года назад
max is used by #include
@abuzaid4342
@abuzaid4342 2 года назад
this man was a genius
@ashu3707
@ashu3707 3 года назад
thanks a lot
@vu5700
@vu5700 4 года назад
Whats the output of max function if left is equal to right
@Luna-fu7ix
@Luna-fu7ix 6 лет назад
thank ya a lot
@jr.shivendra4271
@jr.shivendra4271 5 лет назад
it was brilliant...
@krishnasai573
@krishnasai573 8 лет назад
Is it BINARY TREE or BINARY SEARCH TREE..... There is a lot of difference between those two Binary tree :-Tree where each node has up to two leaves 1 / \ 2 3 Binary search tree :-Used for searching. A binary tree where the left child contains only nodes with values less than the parent node, and where the right child only contains nodes with values greater than or equal to the parent. Hope that this is helpful to anybody :)
@lravikiran88
@lravikiran88 8 лет назад
it is bst
@InfamousBlackGuy
@InfamousBlackGuy 7 лет назад
Wouldn't change the process of finding the height of the tree.
@samruddhipatil1812
@samruddhipatil1812 Год назад
Thanks
@sandeepkumaradvocate4035
@sandeepkumaradvocate4035 6 лет назад
Thanks sir
@T4l0nITA
@T4l0nITA 9 лет назад
really great video, i was wondering, is there a way to implement this function with an iterative algorithm ?
@mycodeschool
@mycodeschool 9 лет назад
T4l0nITA It won't be so intuitive, but yes, any recursion can be implemented using iteration.
@aryanverma7800
@aryanverma7800 2 года назад
@@mycodeschool Are you in hell or heaven right now??
@ramviswanadhapalli4397
@ramviswanadhapalli4397 Год назад
​@@aryanverma7800why the fuck would you ask that brooo
@usama57926
@usama57926 6 лет назад
thank u brother
@nedadra1
@nedadra1 9 лет назад
really helpfull thank u .
@alanliang9538
@alanliang9538 4 года назад
nice vid ma man
@Fauji_Baba
@Fauji_Baba 8 лет назад
thanx mycodeschool u r like god to me ..
@sensen9235
@sensen9235 3 года назад
can you use a static variable?
@vangjelgramozi324
@vangjelgramozi324 6 лет назад
And how do you build the max function? Instead of max(a,b) do you write return ( FindHeight(root->left) > (FindHeight(root->right) ? FindHeight(root->left) : FindHeight(root->right) ); Is this correct or no?
@prasanna5836
@prasanna5836 6 лет назад
Here 'FindHeight' function returns an integer,it's like writing return some_int_1 > some_int_2 ? some_int_1 : some_int_2; which is correct.
@monicaslv323
@monicaslv323 8 лет назад
int findheight(struct nodo *root)...how do you call this kind of function from main()??
@11m0
@11m0 8 лет назад
+M. Santos it will look similar to this public static void main(String[] args) { BinaryTree tree = new BinaryTree(); //This is based on the name of your class tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println("Height of tree is : " + tree.maxDepth(root)); }
@manishbisht7740
@manishbisht7740 6 лет назад
Can anyone tell me how to find height of a tree represented as adjacency list? BTW great video.
@Name-pn5rf
@Name-pn5rf 3 года назад
can we do the if statement as if(node.left==null && node.right==null){ return 0; } I did it and it gave me errors...why did this happen?
@shivamkumarchauhan9648
@shivamkumarchauhan9648 3 года назад
when node is null itself then how it will get value of node->left and node->right?
@dustbunnys
@dustbunnys 6 лет назад
Will this technique work for an AVL tree?
@amandeepsaxena9579
@amandeepsaxena9579 6 лет назад
yes exactly same code will work for AVL trees also
@divyachowdhary2574
@divyachowdhary2574 8 лет назад
awesome
@prashantgupta808
@prashantgupta808 4 года назад
how max function is working here without any definition?
@kayjay1278
@kayjay1278 10 лет назад
can it work for binary search tree also? I mean do we need to make any changes if we want to make this code work for binary search tree instead of binary tree?
@mycodeschool
@mycodeschool 10 лет назад
Binary search tree is only a special kind of binary tree. So, yes , this will work for a binary search tree without any change.
@jaykaushik9516
@jaykaushik9516 2 года назад
Please ellaborate more for finding height of tree
@ES11777
@ES11777 Год назад
0:54 small mistake: you said that the number 3 is a leaf node but it's not.
@vasachisenjubean5944
@vasachisenjubean5944 4 года назад
int height(TreeNode root) { if(root==null) { return -1; } return Math.max(1+height(root.l), 1+height(root.r)); }
@abinavdepp
@abinavdepp 10 лет назад
very nice tutorials. i have a question!. here in this video where do you find the height of the left tree and right. it just returns -1 if root is null na?
@mycodeschool
@mycodeschool 10 лет назад
abinav depp Please watch previous videos in data structures series to understand how recursion works for tree. You will be able to understand how this is working. Introduction to data structures
@hhcdghjjgsdrt235
@hhcdghjjgsdrt235 2 года назад
int MaxDepth(TreeNode root) { if (root == null) return 0; int HOL = MaxDepth(root.left); int HOR = MaxDepth(root.right); if (HOL >= HOR) { return HOL + 1; } else { return HOR + 1; } }
@roushanraj2155
@roushanraj2155 8 лет назад
for count
@sergiojimenez3445
@sergiojimenez3445 7 лет назад
anyone could explain me why is O(n) if this is supossed to check all the branches
@miljan9602
@miljan9602 7 лет назад
Dude, you gave yourself a answer. If it needs to check every branch then it is O(n), n is number of branches and it checked every branch once.
@vladyslavmiachkov7431
@vladyslavmiachkov7431 5 лет назад
But if tree wiill be huge that cause stack overflow of recursion doesnt; it?
@obinnaubah9045
@obinnaubah9045 5 лет назад
Yes. That's why there is a more efficient algorithm. www.afternerd.com/blog/python-check-tree-balanced/
@elusk4545
@elusk4545 6 лет назад
At 1:17, you state the height of the tree is 3... Is root not considered part of the tree?
@dustbunnys
@dustbunnys 6 лет назад
Eric Lusk, you can think about it as number of nodes -1 if you want to include the root as part of the tree.
@bhartendukumar880
@bhartendukumar880 4 года назад
has someone tried this in c++? anyone has the code for it?
@sgg2037
@sgg2037 5 лет назад
Hi, do you have a lesson on finding Floor and Ceil from a Binary Search Tree? Thanks.
@shyam5631
@shyam5631 5 лет назад
he is dead.
@SWAPNILMISHRABLC
@SWAPNILMISHRABLC 2 года назад
@@shyam5631 no he is not. His friend died and not him
@rashmih8774
@rashmih8774 9 лет назад
somebody reply please dont we have to make a count here !! like we have to increment the count each time we parse right !
@KrishnaKr
@KrishnaKr 9 лет назад
Rashmi H Thats the beauty of recursion...You need to see previous lectures on binary trees... :)
@VikasYadav-vy4wd
@VikasYadav-vy4wd 7 лет назад
the addition is taking place in this line of code "return max(FindHeight(root->left), FindHeight(root->right)) + 1;" The +1 is always performed after the function is finished being called. We find the lowest depth of the tree and then we break the recursive search for the bottom with (root == null), and we send -1 + 1 = 0 which goes back up and becomes 0+1= 1 which goes back up and becomes 1+1 = 2 which goes up and so on and so on... until we close all the recursive calls.
@GamersCreedTeam
@GamersCreedTeam 6 лет назад
Thanks!
@souravraj9505
@souravraj9505 5 лет назад
@@VikasYadav-vy4wd plz explain the counting more clearly...
@Aman-vd3tr
@Aman-vd3tr 5 лет назад
@@souravraj9505 every time function is used(recursion function) it increments its value by 1
@usama57926
@usama57926 6 лет назад
amazing algorithm
@watchit186
@watchit186 9 лет назад
sir ..nicely done...but one thing i didn't get...nowhere count is incremented.. last leaf node returning -1 to its parent node..but wat its parent node returning to its parent node..its totally confusing..can u explain bit more on this..
@JonathanWexlerConnect
@JonathanWexlerConnect 9 лет назад
ravi kumar In the actual code, he returns Max of two options (left node and right node), and adds 1 to whichever is bigger. That in turn returns to whichever node before that called the recursive function, and that call will also add 1. This continues for each node in the tree until it reaches the root node, which will add 1 to the final result, and return that Integer value to whoever called the function originally. In other words: null leaf returns -1, the node before takes the -1 and adds 1 (=0), the node before that takes the 0 and adds 1 (+1).....(nDepth-1)
@AhmedMahmoud-qu6nq
@AhmedMahmoud-qu6nq 9 лет назад
Jonathan Wexler so please can you explain how the stack works with the line return max (findheight(root->left),findheight(root-.right)); mycodeschool
@inclinedscorpio
@inclinedscorpio 5 лет назад
*Return 0 not -1 because the number is returned to parent of leaf node and not the leaf node !!*
@biochem7092
@biochem7092 7 лет назад
if (root is Null) it should return 0. Because it means, that the upper level node will take it as 0. Code runs line by line, and when it returns, the function is finished, so it won't add +1 to 0. It is fine, that when root is Null, return 0. Please watch other videos and learn from their lectures. I do not agree that you are returning -1 for this function.
@earthwombat
@earthwombat 6 лет назад
i think you were confused by the recursion and which node is which. It will not return at ```if (root == null)``` for node 7 because it is not null, but the leaves are.
@ziddy26
@ziddy26 8 лет назад
how come the height of node 2 is 2?by your definition of height, isn't it is supposed to be 1. If it is 2, then the height of the tree should be 4.
@mehedihasanhridoy1701
@mehedihasanhridoy1701 4 года назад
yeah i also don't get it
@souravraj9505
@souravraj9505 5 лет назад
plz explain how counting is happening?
@random-0
@random-0 5 лет назад
if you dont understand recursion then just write down all the step on paper then you will definately understand
@amateurbeginner7538
@amateurbeginner7538 7 лет назад
yeahhhhh
@siddharthmagadum16
@siddharthmagadum16 3 года назад
what about the root node being null? the height would be -1? or still 0? . According to the code it is -1 , but I'm doubting on it ...
@siddharthmagadum16
@siddharthmagadum16 3 года назад
@@bgmishortmoments Hmm, now I would think that just returning -1 is correct as there will be no tree at all if root is null. And Answer would be 0 in case of only 1 node(root).
@bgmishortmoments
@bgmishortmoments 3 года назад
@@siddharthmagadum16 yah I too realized now
Далее
Delete a node from Binary Search Tree
18:27
Просмотров 1,1 млн
ЮТУБ ТОЧНО ВСЕ!
11:23
Просмотров 596 тыс.
Reverse a string or linked list using stack.
16:25
Просмотров 383 тыс.
Top 7 Algorithms for Coding Interviews Explained SIMPLY
21:22
Inorder Successor in a binary search tree
17:58
Просмотров 359 тыс.
Infix to Postfix using stack
18:20
Просмотров 747 тыс.
Binary tree traversal: Preorder, Inorder, Postorder
14:29