Тёмный

Invert Binary Tree | Leetcode  

Techdose
Подписаться 176 тыс.
Просмотров 56 тыс.
50% 1

This video explains a very basic recursion type problem which is frequently asked in interviews which is to find the mirror image of a given binary tree.Mirror image of a binary tree is also called as inversion of a binary tree.Solving this problem by constructing a new binary tree is not a correct approach.We need to just change the pointers and invert the binary tree inplace. I have explained the inplace binary tree inversion algorithm using recursion by showing proper examples. At the end of the video, i have also shown the code walkthrough for the inversion algo. CODE LINK is present below as usual. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)
=================================================================
INSTAGRAM: / surya.pratap.k
LinkedIn: / surya-pratap-kahar-47b...
=================================================================
CODE LINK: gist.github.co...
SIMILAR PROBLEM:-
Postorder traversal without recursion: • Postorder traversal wi...
simplest way to find preorder given inorder and postorder: • simplest way to find p...

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

 

30 сен 2024

Поделиться:

Ссылка:

Скачать:

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

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 157   
@niveditha-7555
@niveditha-7555 4 года назад
I was watching comedy show and boom!! advertisement came: "do you know what’s the scariest thing is, not knowing how to invert a binary tree in a coding interview" and I ended up being here😂 thank you Algo expert ad😂😂😂
@techdose4u
@techdose4u 4 года назад
😂 Hahahahaa
@scxdb9848
@scxdb9848 4 года назад
@@darshitpandey8642 Oh wow. I'm not alone!!!
@souravraychaudhuri6600
@souravraychaudhuri6600 4 года назад
I wonder who wouldn't know how to invert a binary tree... this is one of the easiest algorithms.
@techdose4u
@techdose4u 4 года назад
@@souravraychaudhuri6600 Most students are beginners :)
@souravraychaudhuri6600
@souravraychaudhuri6600 4 года назад
@@techdose4u I meant those who are sitting for a coding interview.
@aryan7069_
@aryan7069_ 3 года назад
It was overhyped.. i was too afraid. But it looks easy after you explained it . Thanks
@techdose4u
@techdose4u 3 года назад
😂
@shubhamkumargupta3478
@shubhamkumargupta3478 4 года назад
Telling TIme Complexities in every video would be cherry on the cake. Your videos are really good. Especially the video you talk about how to crack any interview exam. 😍😍 There is swap also in STL so this can be like this also. TreeNode* invertTree(TreeNode* tree) { if(!tree)return tree; invertTree(tree->left); invertTree(tree->right); swap(tree->left,tree->right); return tree; }
@techdose4u
@techdose4u 4 года назад
Nice :P
@ArpitDhamija
@ArpitDhamija 4 года назад
Can you make a complete series on Trees, LinkedList , OS and DBMS
@techdose4u
@techdose4u 4 года назад
Will continue.
@kasyapdharanikota8570
@kasyapdharanikota8570 3 года назад
why was postorder traversal used? why not others?
@techdose4u
@techdose4u 3 года назад
Try preorder
@kasyapdharanikota8570
@kasyapdharanikota8570 3 года назад
@@techdose4u understood ; it is working for preorder ,inorder postorder.
@israelmcculley2927
@israelmcculley2927 3 года назад
I'm downvoting this video simply because the writing is illegible.
@techdose4u
@techdose4u 3 года назад
😅
@surbhitamrakar1638
@surbhitamrakar1638 4 года назад
The way you explain is amazing..you made the problem cakewalk.a big thanks to you.😅
@techdose4u
@techdose4u 4 года назад
Welcome :)
@pranavsharma7479
@pranavsharma7479 2 года назад
time complexity = O(n) as traversal is used Space complexity - O(n) internal stack space
@CodeEx7
@CodeEx7 Год назад
SC will be O(h), where h is Height of tree.
@DeepakGupta-zz1vf
@DeepakGupta-zz1vf 4 года назад
can we add one more condition like root->left == NULL && root->right == NULL return . Because again swapping NULL with NULL doesnt makes sense. Am I thinking correct???
@sneha_2005
@sneha_2005 4 года назад
Thanks. You put in a lot of effort.
@techdose4u
@techdose4u 4 года назад
Welcome :)
@pooblock4092
@pooblock4092 3 года назад
Great video. Definitely made it super easy to understand compared to those big youtubers. Thanks!
@amitavamozumder73
@amitavamozumder73 3 года назад
adding another check may help avoid the unnecessary null swapping at the root level. :)
@SonicGal007
@SonicGal007 3 года назад
When you accent is this thick, you really need to include subtitles in your video. Just speak in your native language because people struggle to understand you and it's very demoralizing to novice coders.
@techdose4u
@techdose4u 3 года назад
I tried to include subtitles but auto-generated ones are poor so couldn't include. By the way, which country are you from ?
@SonicGal007
@SonicGal007 3 года назад
United States. If the auto generated subtitles are inaccurate, you have to add them manually. I understand that it's a time consuming thing to do, but it would be helpful when your accent makes certain words incoherent. Many English speaking videos offer subtitles (not auto generated) in a wide array of languages. But that's just my suggestion. I appreciate your reply!
@techdose4u
@techdose4u 3 года назад
It will be great to get it on RU-vid because time is my enemy 😅
@punjabicodingstyle5111
@punjabicodingstyle5111 4 года назад
Wow,june challenge is also here
@techdose4u
@techdose4u 4 года назад
👍
@ottyudo7208
@ottyudo7208 4 года назад
Thanks for this... Do any swaps happen at 1:35? I mean that does our program actually get to swap the None values on the root node of 1?
@techdose4u
@techdose4u 4 года назад
No need to swap when you are at leaf node. Even if you swap, the answer will be same.
@HARIkRISHNA-km5cy
@HARIkRISHNA-km5cy 4 года назад
Can you recommend me any book DS and Algorithms ? I am a beginner
@techdose4u
@techdose4u 4 года назад
Ds & Algo by Narsimha Karumanchi.
@prateekmahajan5490
@prateekmahajan5490 2 года назад
Earlier thought the toughest, but now it seems the easiest. Thank you RU-vidr.
@meghamalviya8495
@meghamalviya8495 4 года назад
Thanks!..I want to clarify one thing that will this code also swap the null values of the leaf node(when leaf node becomes the root or curr)?
@techdose4u
@techdose4u 4 года назад
Yes correct.
@garychap8384
@garychap8384 3 года назад
How is this a recursive problem ? They're the exact SAME graph! sure, you could do ... *Method 1* void Node::Reverse() { // Swap left and right pointers... Node* ptrTemp = ptrLeft; ptrLeft = ptrRight; ptrRight = ptrTemp; // And have all children do same, recursively! (ptrLeft)->Reverse(); (ptrRight)->Reverse(); } ... and then simply call head.Reverse(); But you'd need to hide it behind a Tree class, or risk a caller accidentally calling Reverse on a non-head node and possibly corrupting the tree. But what's wrong with... *Method 2* // In type 'Node' private: Node* ptrChild[2]; // child nodes are [0] and [1] ... and reverse by simply inverting the index ... i = 1 - i; Or... *Method 3* Nodes can share a static pair of index variables... uint _left = 0 uint _right = 1 Then you just : swap values of _left and _right; on ANY node... and, being shared, the whole tree is reversed - Because your operations use : ptrChild[_left] and ptrChild[_right] Better... *Method 4* Just put your operations and a 'sense' variable in the Tree class, make the Nodes nice and efficient data-only PDTs... ... and thus do away with the need to propagate the 'sense' of the tree at all ! *Recursion Rant* Recursion is evil... yes, even in TCO languages. The stack is a precious resource, stack exhaustion will stop you from scaling, heavy stack use is non-portable, stack exhaustion won't show up in the debugger ... TCO_Reliance eases stack burden but confines your breadth/depth decisions... If you call such recursive code, from code which is itself recursive - all hell can break loose... and it's most likely to wait till you hit a production environment. : / And even if it works... You cannot readily pause, trim, save or restore the call stack, nor can you rebalance the work across cores or machines. You also cannot trim the call stack as a result of new facts learned during the search (dead ends) ... it's why God invented the Queue. Queues live in the heap, not the stack. They can be paused, saved, loaded, trimmed, filtered and load-redistributed! Best of all, queues can be processed from a thread pool, efficiently, on any architecture! And they'll scale, save, load, filter and trim nicely as they're on the heap! Basically, if the answer is _"recursion"_ ... then the question is stupid! So, stop it! Or, y'know... don't... but know that you WILL be among the first against put up against the wall for war-crimes when the robots rise up and see how you've treat their ancestors!
@learnhumanity6701
@learnhumanity6701 2 года назад
This is code is good if we just have to write the function for the program in the platform like Leetcode. But, incomplete if we have to implement a complete program.
@Chaloobolo
@Chaloobolo 2 года назад
TechDose If you are launching any course. What will be the problem in telling course fees how much you charged in the last batch? At least someone can't wait for your sweet time to respond right?
@ebrahimbonger3950
@ebrahimbonger3950 2 года назад
Java solution: class Solution { public TreeNode invertTree(TreeNode root) { if(root == null) return null; invertTree(root.left); invertTree(root.right); swapNodes(root); return root; } public void swapNodes(TreeNode root) { TreeNode temp = root.left; root.left = root.right; root.right = temp; } }
@tanmay6670
@tanmay6670 4 года назад
man you are awesome ....hope we will see more lectures coming from you !!!!!!!!!!111
@techdose4u
@techdose4u 4 года назад
Yep...thanks
@manideepgupta5438
@manideepgupta5438 2 года назад
What if the given binary tree is incomplete binary tree, I think thise approach fails
@anmolwadali9227
@anmolwadali9227 4 года назад
sir plz also make a playlist companies wise technical interview problems
@gorkimcgregor8137
@gorkimcgregor8137 4 года назад
I would be helpful if you do the python3 coding too.
@techdose4u
@techdose4u 4 года назад
I never use python for programming. Only cpp 😅 Not possible to cover all languages due to less time.
@jsarvesh
@jsarvesh 3 года назад
# edge case if not root: return None # initialize deque with root from collections import deque Q = deque([root]) result = list() while Q: # popleft node from Q node = Q.popleft() if node: # swap left and right child node.left, node.right = node.right, node.left # add left and right child to Q Q.append(node.left) Q.append(node.right) return root
@HarshKumar-nh6be
@HarshKumar-nh6be 4 года назад
Made easy😄😄❤
@techdose4u
@techdose4u 4 года назад
😀
@kunalsoni7681
@kunalsoni7681 4 года назад
This question I was seen in Amazon interview 😊.. This solutions is such a beautiful and in a well maintained way☺️😇 you are explaining.. thank you sir to give us solutions..
@utkarshsharma6650
@utkarshsharma6650 2 года назад
just get into the depth and swap the child nodes recursively
@agileprogramming7463
@agileprogramming7463 4 года назад
Sir will the space complexity be O(d) where d is the depth of the Binary Tree or O(n)?
@techdose4u
@techdose4u 4 года назад
O(N) because changing pointers doesn't depend on depth of tree. We need to repeat this for all nodes.
@agileprogramming7463
@agileprogramming7463 4 года назад
@@techdose4uThanks sir :)
@techdose4u
@techdose4u 4 года назад
👍
@ShubhamMahawar_Dancer_Actor
@ShubhamMahawar_Dancer_Actor 4 года назад
you stopped making leetcode july questions solution approach?
@techdose4u
@techdose4u 4 года назад
Because I said I will cover DP & GRAPH questions when it comes. If hard problem comes then I will do it.
@md_aaqil8027
@md_aaqil8027 4 года назад
Java solution class Solution { public TreeNode invertTree(TreeNode root) { if(root==null) return root; else { invertTree(root.left); invertTree(root.right); TreeNode t; t=root.left; root.left=root.right; root.right=t; } return root; } }
@techdose4u
@techdose4u 4 года назад
👍
@paragroy5359
@paragroy5359 4 года назад
sir space complexity should be o(logn) or o(n).I think it should be o(logn),As at the max no of function loaded on the call stack is equal to the depth of the tree. Please clear my doubt???? Thanks for the video....
@techdose4u
@techdose4u 4 года назад
But the tree can also be a skewed tree which makes depth of tree = no of nodes.
@amans6504
@amans6504 3 года назад
Hey dude, why nick white's solution is so short??
@1better520
@1better520 4 года назад
Thankyou :)
@techdose4u
@techdose4u 4 года назад
Welcome :)
@cloud5887
@cloud5887 4 года назад
Thanks for the video. Mind if I ask what mic you are using to record?
@techdose4u
@techdose4u 4 года назад
Boya
@garumugam4480
@garumugam4480 4 года назад
I solved it by performing swap before doing recursive calls. It worked for me. Does it matter? Also I was thinking how to solve this problem using iterative approach? I see it may take space but just wanted to know how to solve.. any clue?
@techdose4u
@techdose4u 4 года назад
You can swap pointers before or after. Both will work. Apply BFS for iterative approach. Recursion is nothing but DFS.
@paraschawla3757
@paraschawla3757 4 года назад
Informative as always, which tool you're using for drawing?
@techdose4u
@techdose4u 4 года назад
Wacom pro inkspace sketch.io
@sadmanpranto9026
@sadmanpranto9026 2 года назад
you need to fix how you write small "r"
@AmazingWorld-fw9oc
@AmazingWorld-fw9oc 3 года назад
Hi. Is this method Correct? We can convert it to dll then we have preorder and in order and we can then reverse the in order and preorder and then construct B tree from reversed inorder and preorder. eg : consider Bt from your video inorder is 123467 reverse inorder is 764321 postorder is 421376 reverse postorder is 476213 and then construct the tree in o(n ) time, yeah, I know your method is very much better but just wanted to ask we can do like this or not?
@vamsishankar2825
@vamsishankar2825 4 года назад
can you recommend me Best book for data structures and algorithms in c++ or java?
@NaveenKumar-br7wb
@NaveenKumar-br7wb 4 года назад
data structures and algorithms made easy by narashima karumanchi
@garimaagrawal5937
@garimaagrawal5937 3 года назад
sir can you make a video on reverse alternate levels of perfect binary tree in O(n) time complexity and O(h) space. I tried but i am uanble to solve. It would be a great help.
@techdose4u
@techdose4u 3 года назад
Please let me know when I start Tree DS.
@aleyummusic
@aleyummusic 4 года назад
What does the call stack look like?
@techdose4u
@techdose4u 4 года назад
It's a recursion call stack. You can try by dry running the same.
@aleyummusic
@aleyummusic 4 года назад
@@techdose4u dry running?
@namaloompakistani1768
@namaloompakistani1768 2 года назад
thank you sir
@techdose4u
@techdose4u 2 года назад
Welcome 😄
@anuragsoni2256
@anuragsoni2256 3 года назад
Nice logic. We can also use pre order and keep on changing the left and the right pointers while traversing the the tree, but your logic is more enjoyable.
@techdose4u
@techdose4u 3 года назад
👍
@anonymoussloth6687
@anonymoussloth6687 4 года назад
Can we invert a Binary tree in any other order other than postfix? In this video, it says to go left, then right, then to the actual node it self so: LRN which is post fix. What if we did LNR or NLR? or what if we did it breath first where we swap the left and right nodes of all the nodes in the same level? Basically, my question is does it have to be postfix and, if so, why?
@techdose4u
@techdose4u 4 года назад
No. Preorder and inorder should work too. Just try it. I just randomly took postorder out of 3 available options.
@camychhetri
@camychhetri 3 года назад
Thank you 😊
@techdose4u
@techdose4u 3 года назад
Welcome
@jeyans6759
@jeyans6759 3 года назад
how to print it (mirror image of tree)
@mehershrishtinigam5449
@mehershrishtinigam5449 2 года назад
Space Complexity ?
@abhijeetkumar2204
@abhijeetkumar2204 4 года назад
Great explanation,are you still working in Samsung?
@techdose4u
@techdose4u 4 года назад
Yes
@abhijeetkumar2204
@abhijeetkumar2204 4 года назад
@@techdose4u can you support me with referral in future.I am now in 6th sem from a private University.Where we don't get interviewed at any product based company.thank you.
@alexwallen7168
@alexwallen7168 4 года назад
Good stuff!
@techdose4u
@techdose4u 4 года назад
Thanks
@manasvinsharma1740
@manasvinsharma1740 3 года назад
A easy level coding question with just a scary name 😂😂
@oqant0424
@oqant0424 Год назад
thank u so much
@sharangkulkarni5718
@sharangkulkarni5718 4 года назад
Ty bhaiya
@techdose4u
@techdose4u 4 года назад
Welcome :)
@BringMe_Back
@BringMe_Back 2 года назад
thanks bro;
@amitkumargupta6722
@amitkumargupta6722 3 года назад
Thank you such much for easiest solution.....
@techdose4u
@techdose4u 3 года назад
Welcome
@garychap8384
@garychap8384 3 года назад
Surely, the easiest solution is to realise that the two trees are exactly the same ... then arch a weary eyebrow at your interviewer and subtly imply that he's an idiot ; ) Then, solve it anyway... First, the stupid way, in linear time... saying all the while why it's all rather silly. Then offer to rewrite his B-Tree so that it doesn't care, and he can reverse the sense of it as much as he wishes, in fixed time! ... otherwise, he'll be fixing this in every application - not to mention spanking the stack till it hurts, like a teenager with a pornhub subscription XD
@chethankumarbn6147
@chethankumarbn6147 2 года назад
Concept is explained very well, but before calling left and right i,e swap(curr -> left) and swap(curr - > right), it's good add null check before calling it. if left node is exist then call for swap(curr -> left) otherwise not. it won't make any difference in output. but larger input it will reduce lots unnecessary recursion call for null values.
@deepakprajapati5064
@deepakprajapati5064 3 года назад
Simplest solution thank your 😊
@techdose4u
@techdose4u 3 года назад
Welcome
@hemanthram4369
@hemanthram4369 4 года назад
performing a dry run on algo at the end of video will be more helpful.
@techdose4u
@techdose4u 4 года назад
Dry run was during the explanation. Code was just as I had explained.
@NikhilKumar-oy7mx
@NikhilKumar-oy7mx 4 года назад
if you want at the end, run by yourself. video is already too long
@santoshbhupati3579
@santoshbhupati3579 Год назад
Thanks🤘🤘🤘
@CoffeeXmusic
@CoffeeXmusic Год назад
Thank you, very clear visual explanation
@punjabicodingstyle5111
@punjabicodingstyle5111 4 года назад
Sir from.where you got your computer science degree.
@techdose4u
@techdose4u 4 года назад
Follow LinkedIn
@punjabicodingstyle5111
@punjabicodingstyle5111 4 года назад
Ok,got it
@prasannapm3220
@prasannapm3220 2 года назад
thank you
@ryanaugustine5940
@ryanaugustine5940 2 года назад
You can also do this using PreOrder traversal.
@HimanshuSingh-ob9qo
@HimanshuSingh-ob9qo 4 года назад
👍
@techdose4u
@techdose4u 4 года назад
👍
@azeezsayyad7281
@azeezsayyad7281 4 года назад
you are great u put lots of efforts
@techdose4u
@techdose4u 4 года назад
Thanks :)
@abantikatonny
@abantikatonny 2 года назад
Thank you so much for the detailed explanation of how recursion works here :)
@Learner010
@Learner010 4 года назад
expecting recursion process in more details but overall i get the logic; thanks
@techdose4u
@techdose4u 4 года назад
👍
@mostinho7
@mostinho7 4 года назад
This isn’t actually a mirror image, it’s a reflection on the y axis, but great video! Solution: Doing a post order traversal (visit left node, visit right node, then visit root) when we finally visit the root (after recursion) we switch the pointers, left node becomes right and right becomes left
@techdose4u
@techdose4u 4 года назад
Yea
@mostinho7
@mostinho7 4 года назад
TECH DOSE thank you for making these! Keep it up. Subscribed!
@techdose4u
@techdose4u 4 года назад
Yea sure :)
@rms7585
@rms7585 4 года назад
Thanks for this great video sir! Can you please solve leetcode #410 split array largest sum?
@spetsnaz_2
@spetsnaz_2 4 года назад
i think this problem can be solved using Painter's Partition Problem using DP or using Binary Search. He has made separate videos on these topics. Binary Search : ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-SiE1XFhYoaA.html DP : ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-zNVT8SnGRig.html
@rms7585
@rms7585 4 года назад
@@spetsnaz_2 Oh okay! Thanks a lot!
@randomrandom316
@randomrandom316 4 года назад
class Solution: def invertTree(self, root: TreeNode) -> TreeNode: if not root: return root temp = root.left root.left = root.right root.right = temp self.invertTree(root.left) self.invertTree(root.right) return root For those looking for python3 solution
@techdose4u
@techdose4u 4 года назад
👍
@saikiran901
@saikiran901 4 года назад
Pls explain in java
@techdose4u
@techdose4u 4 года назад
Can't do multiple languages bro 😅 please follow leetcode discussions for java code.
Далее
Making an Algorithm Faster
30:08
Просмотров 90 тыс.
Teeth gadget every dentist should have 😬
00:20
Просмотров 975 тыс.
#慧慧很努力#家庭搞笑#生活#亲子#记录
00:11
pumpkins #shorts
00:39
Просмотров 30 млн
I Solved 100 LeetCode Problems
13:11
Просмотров 37 тыс.
Compiled Python is FAST
12:57
Просмотров 111 тыс.
How Binary Search Makes Computers Much, Much Faster
6:51
Invert Binary Tree - Leetcode 226 - Trees (Python)
6:40
Being Competent With Coding Is More Fun
11:13
Просмотров 84 тыс.
Learn Recursion in 8 minutes 😵
8:19
Просмотров 77 тыс.
Is Computer Science still worth it?
20:08
Просмотров 349 тыс.
LeetCode was HARD until I Learned these 15 Patterns
13:00
Remove K digits | Build lowest number | Leetcode #402
15:30
Teeth gadget every dentist should have 😬
00:20
Просмотров 975 тыс.