L20. Boundary Traversal in Binary Tree | C++ | Java

  Рет қаралды 275,561

take U forward

take U forward

Күн бұрын

Пікірлер: 377
@takeUforward
@takeUforward 3 жыл бұрын
Please likeeee, shareeee and subscribeeeeeeee :) Also follow me at Insta: Striver_79 At 04:35, i have mistakenly told inorder n written preorder. Both of them will work, its just that you need to take the first from left.. :)
@raushanraj6054
@raushanraj6054 3 жыл бұрын
yes, that's what I figured out , when I came to comment the same thing , I just saw this comment of yours. Btw you are doing a great job. Love and support++
@shivamsinha5554
@shivamsinha5554 3 жыл бұрын
Is leaf function is not writeen bhaiya?
@takeUforward
@takeUforward 3 жыл бұрын
@@shivamsinha5554 description pe code hai, wahan se dekh lijie.. In screen it was not visible as it was at upper portion
@9893011111
@9893011111 3 жыл бұрын
why videos stopped coming Raj !
@shubamgoswami
@shubamgoswami 3 жыл бұрын
@@shivamsinha5554 bro pepcoding sa karke dekh ek abr level 1 sa i have learned from there
@subhamengine1143
@subhamengine1143 3 жыл бұрын
The isleaf funtion is: bool isleaf(Node* root){ if(!root->left and !root->right) return true; else return false; }
@harshbhagwani7769
@harshbhagwani7769 3 жыл бұрын
no neeed to write else it will be time taking
@corporatebhai1703
@corporatebhai1703 3 жыл бұрын
@@harshbhagwani7769 nope it gives wrong answer try it yourself
@SHASHANKRUSTAGII
@SHASHANKRUSTAGII 2 жыл бұрын
@@corporatebhai1703 you know the right answer?
@chandantaneja6388
@chandantaneja6388 2 жыл бұрын
@@harshbhagwani7769 its necessary to write leaf function as there is no inbuilt function for tree to check whether its leaf node or not
@arpitgupta2358
@arpitgupta2358 2 жыл бұрын
@@chandantaneja6388 TO USNE KAB KHA HAI KI LEAF FUNCTION MAT LIKHO? HE SAID ABOUT THE ELSE PART OF THE CODE OF LEAF FUNCTION
@anshumaan1024
@anshumaan1024 Жыл бұрын
In leaf Traversal, any traversal ( Preorder, Inorder, Postorder ) will work because we are printing left subtree first before right subtree I hope this helps 🙂
@sahillodha6084
@sahillodha6084 Жыл бұрын
Thank youuu .... Was thinking about that only cause in all traversals left comes before right so any will work
@vikasreddyravulapalli5562
@vikasreddyravulapalli5562 Жыл бұрын
yesss i was thinking the same
@rishabhgupta1222
@rishabhgupta1222 5 ай бұрын
yes that's ryt
@yatharththakare6006
@yatharththakare6006 5 ай бұрын
Yes any will help but, Post order can be efficient, Cause it traverse along leaf values first. If you write it on a paper you will understand the order. Left - Right - Root. Correct me if i m wrong.
@saurabh0065
@saurabh0065 2 ай бұрын
but if i have on leaf node why to recursively travel to left and right ?
@rohan8758
@rohan8758 Жыл бұрын
When i listen word as inOrder(LDR) traversal, i thought it was preOrder(DLR). Then i read comments & get to know you corrected and pinned that point, when i read more comment, i was thinking to switch from this video & look for another video for same problem. But i watch whole video & remembered that never judge a book from its cover, Although here cover is also very famous among developers in IT. 😊😊😊
@aysams2
@aysams2 Жыл бұрын
For anyone wandering here is the isLeaf( ) fucntion: bool isLeaf(TreeNode *root) { return !root -> left && !root -> right; }
@sautramanivibhuti4597
@sautramanivibhuti4597 Жыл бұрын
Do we have to define this function or its predefined ?
@aysams2
@aysams2 Жыл бұрын
@@sautramanivibhuti4597 We need to define it ourselves. My code wasn't running bcz I hadn't defined it earlier. So was letting you know.
@sautramanivibhuti4597
@sautramanivibhuti4597 Жыл бұрын
@@aysams2 thanks man 🤝
@aysams2
@aysams2 Жыл бұрын
@@sautramanivibhuti4597 No worries 🤝
@pragatiagrawal201
@pragatiagrawal201 2 жыл бұрын
Leetcode has now added this question in their premium subscription now....but GFG is also good.. :)
@GurpreetSingh-ps6kl
@GurpreetSingh-ps6kl 2 жыл бұрын
true lol
@dhruvrawatt9
@dhruvrawatt9 11 ай бұрын
and coding ninjas also
@likhith8434
@likhith8434 10 ай бұрын
Yeah@@dhruvrawatt9
@morhadi
@morhadi 6 ай бұрын
do you guys have link?
@safiwasif2905
@safiwasif2905 4 ай бұрын
@@morhadi link mili kya
@tanmoychakraborty1471
@tanmoychakraborty1471 2 жыл бұрын
The addLeaves function is done in PRE-ORDER form but it should be IN-ORDER. Updated Code for addLeaves(Node root, List ans): Language: JAVA (change accordingly for other languages) private static void addLeaves(Node root, List ans) { if (root.left != null) addLeaves(root.left, ans); //LEFT if (isLeaf(root)) { ans.add(root.val); //ROOT return; } else if (root.right != null) addLeaves(root.right, ans); //RIGHT }
@ShivamGupta-mq8yw
@ShivamGupta-mq8yw 2 жыл бұрын
Yes that should be preorder traversal
@antibarcelona2123
@antibarcelona2123 Жыл бұрын
won't matter since the left and right node are gonna be null anyways, pre, in or post, any will work
@Sumeet_100
@Sumeet_100 Жыл бұрын
You are correct bro it should be inorder
@parthmittal5625
@parthmittal5625 3 жыл бұрын
Coded on my own just after listening to the approach!! 🙇
@lalitkashyap8167
@lalitkashyap8167 2 жыл бұрын
can you pls tell leetcode problem number,I guess this problem is in premium subscription of leetcode
@piyushacharya7696
@piyushacharya7696 2 жыл бұрын
@@lalitkashyap8167 use GFG
@siddhantkashyap4802
@siddhantkashyap4802 Жыл бұрын
Best feeling 💪
@jatinkashyap9986
@jatinkashyap9986 5 ай бұрын
​@@lalitkashyap8167gfg tree boundary traversal
@manasjena5124
@manasjena5124 2 ай бұрын
Bhai code implementiion ka link kidhar hai .bhai please help me
@magnitegame
@magnitegame 3 жыл бұрын
I have done binary tree early also but they were just explaining gfg solutiions but u teach us intuition how u got the approach and all great work
@manasjena5124
@manasjena5124 2 ай бұрын
Bhai code implementiion ka link kidhar hai bhai please help me
@sugnickpramanik7098
@sugnickpramanik7098 3 жыл бұрын
4:53 minutes I think it should left root right....🙂...@take u forward....or striver vaiya❤..lovely content💖
@mandeep2192
@mandeep2192 2 жыл бұрын
it shud be preordr traversal...
@_SOHAMSAMANTA
@_SOHAMSAMANTA 2 жыл бұрын
Thanks for including those questions too which required LeetCode Premium subscription.
@shivangisrivastava1158
@shivangisrivastava1158 3 жыл бұрын
yes Understood !!! 👏 Boundary traversal amazingly explained
@lifehustlers164
@lifehustlers164 Жыл бұрын
Completed 21/54 (38% done) !!!
@kanishq8684
@kanishq8684 4 ай бұрын
Bhaiya, you teach really well, but for this question, it would have been better to use another example to make the concept clearer. For instance, a tree that has a node which is not a leaf node and has both a left child and a right child, where neither of these children are leaf nodes."
@stith_pragya
@stith_pragya Жыл бұрын
Thank You So Much for this wonderful video.........🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻🙏🏻
@siyonabansal3854
@siyonabansal3854 2 ай бұрын
def boundary_trvarsel(self): # anticlockwise print(self.root.data) self.preorder(self.root.left_child) self.postorder(self.root.right_child)
@Weirdvloggertrue
@Weirdvloggertrue 3 жыл бұрын
The series is amazing! ❤️ When you will be uploading the next set of videos?
@RAGHAVGOYAL-w8b
@RAGHAVGOYAL-w8b Жыл бұрын
I think we should consider for the root node if there is a left child then we should consider the left boundary otherwise directly start from the boundary and the same for the right boundary this code will not give error in codestudio C++ bool isLeaf(TreeNode* temp) { return temp->left==NULL and temp->right==NULL ; } void leftBoundary(TreeNode* temp,vector&left) { if(temp==NULL) return; while(!isLeaf(temp)) { left.push_back(temp->data); if(temp->left!=NULL) temp=temp->left; else if(temp->right!=NULL) temp=temp->right; } } void bottomBoundary(TreeNode* temp,vector&bottom) { if(temp==NULL) return; if(isLeaf(temp)){ bottom.push_back(temp->data); } bottomBoundary(temp->left,bottom); bottomBoundary(temp->right,bottom); } void rightBoundary(TreeNode* temp,vector&right) { if(temp==NULL) return; while(!isLeaf(temp)) { right.push_back(temp->data); if(temp->right!=NULL) temp=temp->right; else if(temp->left!=NULL) temp=temp->left; } } void solve(vectortemp,vector&finalans) { for(auto it:temp) { finalans.push_back(it); } } vector traverseBoundary(TreeNode *root) { vector finalans; vector left; vector bottom; vector right; leftBoundary(root->left,left); bottomBoundary(root,bottom); rightBoundary(root->right,right); reverse(right.begin(),right.end()); finalans.push_back(root->data); solve(left,finalans); solve(bottom,finalans); solve(right,finalans); return finalans; }
@SRIHARSHAMarella
@SRIHARSHAMarella 9 ай бұрын
hey striver exactly at 4:07 seconds (root left right) is for inorder actually its for pre order
@harshbhagwani7769
@harshbhagwani7769 3 жыл бұрын
PYTHON CODE FOR BOUNDARY TRAVERSAL class Solution: def __init__(self): self.res=[] def isleaf(self,root): if root.left is None and root.right is None : return True return False def addleftboundary(self,root): curr=root.left while(curr): if not self.isleaf(curr): self.res.append(curr.data) if curr.left : curr=curr.left else : curr=curr.right def addrightboundary(self,root): curr=root.right temp=[] while(curr): if not self.isleaf(curr): temp.append(curr.data) if curr.right : curr=curr.right else : curr=curr.left size=len(temp) for i in range(size-1,-1,-1): self.res.append(temp[i]) def addLeaves(self,root): if self.isleaf(root): self.res.append(root.data) return if root.left : self.addLeaves(root.left) if root.right : self.addLeaves(root.right) def main(self,root): if root is None : return self.res if not self.isleaf(root): self.res.append(root.data) self.addleftboundary(root) self.addLeaves(root) self.addrightboundary(root) return self.res obj=Solution() res=obj.main(root) print(res)
@ashtonronald
@ashtonronald 4 ай бұрын
Took some iterations to understand it, thanks for these awesome videos!
@sahithchandraporeddy9787
@sahithchandraporeddy9787 Ай бұрын
Amazing content. Very much appreciate it.
@ritikshandilya7075
@ritikshandilya7075 3 ай бұрын
Thanks for amazing solution striver
@shrad6611
@shrad6611 2 жыл бұрын
(Wrong Sol) is boundary traversal different from root+leftview+bottomview+rightview, if not then why you do something different here it will not work on this tree: 1 2 3 N N 4 5 N N 6 N 7 N , then in bottom view it should print 2 7 6 5, we not include 4 here instead of it as a leave because it covers by 7 so we not include 4 in bottom view Please correct me if I am wrong
@nicks2991
@nicks2991 2 жыл бұрын
yes, the i do think so, the above solution won't work
@_inspireverse___
@_inspireverse___ 2 жыл бұрын
He never said leftview , bottimview or rightview but it is leftboundary + leafnodes + right boundary and every leaf node is at the boundary.
@ayush.kumar_02
@ayush.kumar_02 3 жыл бұрын
Bhaiya i really liked you video and your explanation... plz make a similar DP series 🙏
@babulalyadav4305
@babulalyadav4305 5 ай бұрын
00:01 Discussing the anti-clockwise boundary traversal of a binary tree. 01:23 Boundary traversal of a binary tree discussed 02:36 Traversing the left boundary excluding leaf nodes. 03:46 Traversal strategy for right boundary excluding leaf nodes 05:00 Summarizing the right boundary traversal and reversing the direction 06:11 Boundary traversal in binary tree involves excluding leaf nodes and moving clockwise along the boundary. 07:27 Understanding Boundary Traversal in Binary Tree 08:39 Boundary traversal in a binary tree has O(n) time complexity Crafted by Merlin AI.
@ShivamRaj-be9oy
@ShivamRaj-be9oy Жыл бұрын
Bhaiya your videos are great all your playlists. Especially your DP playlist is great I was scared of DP problems but your explaination made them easy.
@mysteryman2213
@mysteryman2213 Жыл бұрын
what a wonderfull playlist finished till now in a single day
@sathwikmerla6628
@sathwikmerla6628 3 жыл бұрын
Hi Striver please let us know when the remaining lectures will be uploaded... And btw great explanation as usual❤️❤️
@pranaypatadiya
@pranaypatadiya 2 жыл бұрын
Unbelievable explanation....with detailed provided ..in first go code on notepad and first go its right...confident so much... all credit goes to you only.. thank you so much and grateful to you...
@ryanmathew6397
@ryanmathew6397 10 ай бұрын
great question and explanation
@tonyconor681
@tonyconor681 2 жыл бұрын
This is leetcode premium questions but I think it's available in gfg so we can use it for practice this
@bhavkushwaha
@bhavkushwaha 5 ай бұрын
Thankyou Striver, Understood.
@princechoudhary850
@princechoudhary850 2 жыл бұрын
On right subtree the add leave will be node - right first
@somanshukadam7280
@somanshukadam7280 Жыл бұрын
4:05 Correction: Inorder is left root right
@kathanvakharia
@kathanvakharia Жыл бұрын
Amazing explanation. However, note that one can use any of the preorder, inorder and postorder traversals to get the leaf nodes. The reason being, in all three of them, leaves are traversed left to right only!
@pratyushbhatt1712
@pratyushbhatt1712 Жыл бұрын
You can, but we need leaves from left to right in this case, so if you're using postorder, Then you wont get them in that order.
@kathanvakharia
@kathanvakharia Жыл бұрын
@@pratyushbhatt1712 Actually, you will get leaves in left-to-right direction using post order traversal too! Below is my accepted addLeaves function on gfg: void addLeaves(Node* root, vector& ans) { //preorder traversal if(root != nullptr) { if(!isLeaf(root)) { addLeaves(root->left, ans); addLeaves(root->right, ans); } else { ans.push_back(root->data); } } } You can take any tree and run this function, you’ll know leaves are printed from left to right only. The rest functions remain as shown in the video. Thanks :)
@rishabhkumar2062
@rishabhkumar2062 5 ай бұрын
What would happpen if the tree is skewed , then you would repeat certain number of nodes or what if the root has only one child , and the child of root would get repeated????
@aditya14-02
@aditya14-02 3 жыл бұрын
Code thoda tough lag rha hai ..😔 lekin concept achse se samajh.. 👌
@ravichauhan1634
@ravichauhan1634 3 жыл бұрын
Bhaiya pura course hi bana do aap topic wise DSA
@4mulate
@4mulate 4 ай бұрын
for those who tried of a recursive solution this for you (pls give any suggesions to improve this it is very naive) class Solution { public: void leftpart(Node* node,vector &left){ if(node==nullptr) { return; } left.push_back(node->data); if(node->left!=nullptr) leftpart(node->left,left); else if(node->right!=nullptr) leftpart(node->right,left); } void rightpart(Node* node,vector &right){ if(node==nullptr) { return; } right.push_back(node->data); if(node->right!=nullptr) rightpart(node->right,right); else if(node->left!=nullptr) rightpart(node->left,right); } bool isleaf(Node* node){ if(node->left==nullptr && node->right==nullptr) return true; else return false; } void leafpart(Node* node,vector &leaf){ if(isleaf(node)) { leaf.push_back(node->data); return; } if(node->left!=nullptr) leafpart(node->left,leaf); if(node->right!=nullptr) leafpart(node->right,leaf); } vector boundary(Node *root) { //Your code here vector ans,right; ans.push_back(root->data); if(root->left!=nullptr){ leftpart(root->left,ans); ans.pop_back(); } if(root->right!=nullptr){ rightpart(root->right,right); right.pop_back(); } if(isleaf(root)) return {root->data}; leafpart(root,ans); while(!right.empty()){ int top = right.back(); ans.push_back(top); right.pop_back(); } return ans; } };
@abhinavdubey4966
@abhinavdubey4966 3 жыл бұрын
Thank you Bhaiya, you made this question really easy. Keep Going, more power to you.
@nikhilsinghjadon39
@nikhilsinghjadon39 3 жыл бұрын
For leaf nodes you used Pre-Order Traversal..right?
@piyushacharya7696
@piyushacharya7696 2 жыл бұрын
yes
@pushkargarg4946
@pushkargarg4946 5 ай бұрын
that part where we add right child only when left child not present and opposite in right side, did not come intuitively, at least not to me. Still was able to code up after listening to the approach. Thanks
@AppaniMadhavi
@AppaniMadhavi 8 ай бұрын
Here is the total code for C++ class Solution { public: vectorv1,v2,v3; bool leaf(Node* node) { if((node->left==NULL) and (node->right==NULL)) return 1; return 0; } void checkleft(Node* node) { if(node==NULL) return; while(!leaf(node)) { v1.push_back(node->data); if (node->left != NULL) { node = node->left; } else{ node=node->right; } } } void checkleaf(Node *node) { if(node==NULL) return; if(leaf(node)) v2.push_back(node->data); checkleaf(node->left); checkleaf(node->right); } void checkright(Node *node) { if(node==NULL) return; while(!leaf(node)) { v3.push_back(node->data); if(node->right!=NULL) node=node->right; else{ node=node->left; } } } vector boundary(Node *root) { //Your code here int n,i,j; vectorv; if(root==NULL) return v; if(!leaf(root)) v.push_back(root->data); checkleft(root->left); checkleaf(root); checkright(root->right); for(i=0;i
@ManojKumarManuSai
@ManojKumarManuSai 3 жыл бұрын
I feel there is a mistake at 04:35, Inorder Traversal is Left,Root,Right. Wrong order (ie. Root,Left,Right -> Preorder Traversal ) mentioned video. Any way code works fine.
@THEkarankaira
@THEkarankaira 3 жыл бұрын
its preorder not inorder
@aadityabedi3140
@aadityabedi3140 3 жыл бұрын
But the sir said inorder
@takeUforward
@takeUforward 3 жыл бұрын
Yeah my bad, let me pin this..
@manasjena5124
@manasjena5124 2 ай бұрын
Bhai code implementiion ka link kidhar hai .bhai help me
@prabhakaran5542
@prabhakaran5542 4 ай бұрын
Understood ❤❤❤
@satendra6200
@satendra6200 Жыл бұрын
Add check point in addleave function,otherwise it will throw an runtime error if(root->left) addleave(root->left,res); if(root->right) addleave(root->right,res);
@eshaanpandey7353
@eshaanpandey7353 2 жыл бұрын
This is straight up next level teaching.
@tusharbhart7018
@tusharbhart7018 2 жыл бұрын
why we are processing leaf nodes separately? Can't we just apply preorder(root left right) on the right side and preorder(root right left) on the right side and just add them. ans = root + vector_left + rev(vector_right)? here is the code of what i am saying. void helper1(TreeNode* root, vector &v) { if(!root) return; v.push_back(root -> val); helper1(root -> left, v); helper1(root -> right, v); } void helper2(TreeNode* root, vector &v) { if(!root) return; v.push_back(root -> val); helper2(root -> right, v); helper2(root -> left, v); } vector boundaryTraversal(TreeNode* root) { if(!root) return {}; vector ans, v1, v2; ans.push_back(root -> val); helper1(root -> left, v1); helper2(root -> right, v2); reverse(v2.begin(), v2.end()); for(int i : v1) ans.push_back(i); for(int i : v2) ans.push_back(i); return ans; }
@ishangujarathi10
@ishangujarathi10 Жыл бұрын
GOD LEVEL explanation and intuition striverrr
@anubhavdeepankar6681
@anubhavdeepankar6681 4 ай бұрын
shouldn't we add addLeaves() function at the end of addRightBoundary() before reversing as we then would miss 10 and 11 node shown in example ???
@sarangtamrakar8723
@sarangtamrakar8723 2 жыл бұрын
Code in recursion:------------------- class Solution { public List boundaryOfBinaryTree(TreeNode root) { List res = new ArrayList(); if(IsLeafNode(root)==false){ res.add(root.val); } left_side(root.left,res); addingLeafNode(root,res); ArrayDeque st = new ArrayDeque(); addingRight(root.right,st); while(st.isEmpty()==false){ Integer popped = st.poll(); res.add(popped); } return res; } boolean IsLeafNode(TreeNode root){ if(root.left==null && root.right==null){ return true; }else{ return false; } } void left_side(TreeNode node,List arr){ if(node==null){ return; } if(IsLeafNode(node)==false){ arr.add(node.val); } if(node.left!=null){ left_side(node.left,arr); }else{ left_side(node.right,arr); } } void addingLeafNode(TreeNode node,List arr){ if(node==null){ return; } if(IsLeafNode(node)==true){ arr.add(node.val); } if(node.left!=null){ addingLeafNode(node.left,arr); } if(node.right!=null){ addingLeafNode(node.right,arr); } } void addingRight(TreeNode node,ArrayDeque st){ if(node==null){ return; } if(IsLeafNode(node)==false){ st.push(node.val); } if(node.right!=null){ addingRight(node.right,st); }else{ addingRight(node.left,st); } } }
@mriduljain1981
@mriduljain1981 Жыл бұрын
Completed lecture 20 of tree playlist.
@PRASHANTKUMAR-wi9il
@PRASHANTKUMAR-wi9il Жыл бұрын
love u sir !! aaj placed ho gya !!
@PRAXYBEATS
@PRAXYBEATS Жыл бұрын
What would happen for the case when left subtree is null? it should ideally print left subtree of node root->right, then leaves, and the right boundary. @takeUforward . instead of printing just boundary, should we check for left view and right view some that kind of approach?
@plsgivemecat
@plsgivemecat Жыл бұрын
When left subtree is empty, it will first add the root, then it will print the leaves of the right subtree, and finally add the right boundaries in reverse.
@yatharththakare6006
@yatharththakare6006 5 ай бұрын
Instead of writing separate functions for left leaf and right... is it possible to do it in one go? By using in-order traversal? or any other?
@subhammaji1921
@subhammaji1921 Жыл бұрын
hi Striver bhaiya, The time you mentioned that it should be done in Inorder technique. and you told this is root->left->right. But this is preorder.
@anshumaan1024
@anshumaan1024 Жыл бұрын
bhai preorder, inorder, postorder sab chal jayega, kyoki sabme left phle ayega right se, I hope this helps 🙂
@satyampandey5584
@satyampandey5584 3 жыл бұрын
You made it look very simple brother. Thanks
@vakhariyajay2224
@vakhariyajay2224 Жыл бұрын
Thank you very much. You are a genius.
@shreyabirthare374
@shreyabirthare374 4 ай бұрын
I have a doubt: in the first tree, what will be the output if the left of 3 had a node say "12" and the left of node 5 had a node "13". In this case, will the output be 1,2,3,12,5,13,6,10,11,9,8,7
@sahilkatkamwar2431
@sahilkatkamwar2431 4 ай бұрын
Why are we excluding leaves in left boundary and right boundary and calculating them differently ?
@nileshsinha7869
@nileshsinha7869 3 жыл бұрын
Completed till here. Please post next videos soon. Loving it till now❤❤
@apmotivationakashparmar722
@apmotivationakashparmar722 Ай бұрын
Thank you so much.
@rashiverma8259
@rashiverma8259 3 жыл бұрын
was waiting for this tree series for long....thanks alot
@rushyya
@rushyya Жыл бұрын
UNDERSTOOD ! THANK YOU
@ABHIJEETKumar-vj2oy
@ABHIJEETKumar-vj2oy Ай бұрын
@takeUforwaed where is isleaf() implementation??
@onemoretime3144
@onemoretime3144 2 ай бұрын
Why can't we apply pre order traversal for root.left and pos order traversal for root right ?
@jiya8016
@jiya8016 Жыл бұрын
Very helpful. 😍😍
@per.seus._
@per.seus._ Жыл бұрын
understood
@vasujain1970
@vasujain1970 3 жыл бұрын
This is what I needed. Thank you!
@naveen_kotha
@naveen_kotha 3 жыл бұрын
Great Explanation!!
@hardikjain-brb
@hardikjain-brb 6 ай бұрын
Enjoy Guys : class Solution { public: void left(Node* node , vector &v) { if(!node || (!node->right && !node->left)) { return; } v.push_back(node->data); if(node->left)left(node->left,v); else left(node->right,v); } void right(Node* node , vector &v) { if(!node || (!node->right && !node->left)) { return; } v.insert(v.begin(), node->data); if(node->right)right(node->right,v); else right(node->left,v); } void dfs_forleaves(Node* root, vector &ans) { if(!root) { return; } if(!root->left && !root->right) { ans.push_back(root->data); } dfs_forleaves(root->left, ans); dfs_forleaves(root->right, ans); } vector boundary(Node *root) { vector ans; if(!root) return ans; ans.push_back(root->data); if(!root->right && !root->left) { return ans; } left(root->left, ans); dfs_forleaves(root,ans); vector rightv; right(root->right, rightv); ans.insert(ans.end(), rightv.begin(), rightv.end()); return ans; } };
@averagepanda5971
@averagepanda5971 3 жыл бұрын
Keep up the good work BHai🔥🔥🔥
@botchu4597
@botchu4597 2 жыл бұрын
small change when adding right boundary. without using extra temp list and a for loop to add those elements to res list. public void addRightBoundary(TreeNode node) { TreeNode cur = node.right; int index = res.size(); while (cur != null) { if (!isLeaf(cur)) res.add(index, cur.val); if (cur.right != null) cur = cur.right; else cur = cur.left; } }
@piyushacharya7696
@piyushacharya7696 2 жыл бұрын
wow good idea
@vasuchauhan3816
@vasuchauhan3816 3 ай бұрын
Inorder traversal is left, root, right......i guess
@GuruPrasadShukla
@GuruPrasadShukla Жыл бұрын
it is not inorder it is preorder -> Node Left Right
@plsgivemecat
@plsgivemecat Жыл бұрын
Python code: class Solution: def isLeaf(self,node): if not node.left and not node.right: return True def addLeftBoundary(self,root,res): cur = root.left while cur: if not self.isLeaf(cur): res.append(cur.data) if cur.left: cur = cur.left else: cur = cur.right def addLeaf(self,root,res): if self.isLeaf(root): res.append(root.data) return if root.left: self.addLeaf(root.left,res) if root.right: self.addLeaf(root.right,res) def addRightBoundary(self,root,res): stack = [] cur = root.right while cur: if not self.isLeaf(cur): stack.append(cur.data) if cur.right: cur = cur.right else: cur = cur.left while stack: res.append(stack.pop()) def printBoundaryView(self, root): res = [] if not root: return [] if not self.isLeaf(root): res.append(root.data) self.addLeftBoundary(root,res) self.addLeaf(root,res) self.addRightBoundary(root,res) return res
@dhruvmalik8052
@dhruvmalik8052 Жыл бұрын
Nice explanation brother
@jaskaran904
@jaskaran904 2 жыл бұрын
i feel as though this will fail in case we encounter a leaf on before we reach max height inside the tree
@piyushacharya7696
@piyushacharya7696 2 жыл бұрын
it will handle it as well
@piyushacharya7696
@piyushacharya7696 2 жыл бұрын
We will not enter the leaf node in the boundary traversal to the left or right. as a result, the condition never occurs
@jayantsharma_
@jayantsharma_ 2 жыл бұрын
Consider following test case - (from gfg) 4 10 N 5 5 N 6 7 N 8 8 N 8 11 N 3 4 N 1 3 N 8 6 N 11 11 N 5 8 this test case does not have right sub tree of root but there is definitely a right boundary. the question says following about left boundary and right boundary: left : path from root to left most node, preferring left sub-tree tree over right one. right : path from right most node to root, preferring right sub-tree tree over left one. GFG answer: 4 10 5 6 8 11 3 5 8 8 6 11 11 Ur code ans: 4 10 5 6 8 11 3 5 8 6 4 11 11 Both giving different answers, and none have right boundary (1,8,7,5) in answer. Now, we do take left most node of any level even if previously we chose right sub-tree, but if root's right is null, we are not considering right boundary that generated from left sub-tree????
@Rajat_maurya
@Rajat_maurya 2 жыл бұрын
maine kiya gfg pe submit ho gaya
@jayantsharma_
@jayantsharma_ 2 жыл бұрын
@@Rajat_maurya it's more about the doubt instead of accepted code
@mriduljain1981
@mriduljain1981 Жыл бұрын
brooo i did this question on my own finally letss go i am so happy guyzzz
@lifegood6401
@lifegood6401 3 жыл бұрын
Completed all 20 videos. Please Upload More. its been 6 days since 20 and only 20 videos are being uploaded till now.Please try to upload atleast 6-7 videos daily.
@pythonenthusiast9292
@pythonenthusiast9292 3 жыл бұрын
wait karo bhai thoda
@sravan8643
@sravan8643 3 жыл бұрын
class Solution { public: vector ans; Solution(){ ans.resize(0); } vector printBoundary(Node *root) { if(root==NULL) return ans; ans.push_back(root->data); if(root->left!=NULL and (root->left->left or root->left->right)) lefttree(root->left); leaves(root); int n=ans.size(); if(root->right!=NULL and (root->right->left or root->right->right)) righttree(root->right); reverse(ans.begin()+n,ans.end()); return ans; } void lefttree(Node* root){ if(!root->left and !root->right)return; ans.push_back(root->data); if(root->left!=NULL and (root->left->left or root->left->right)) lefttree(root->left); if(root->left==NULL and root->right!=NULL) lefttree(root->right); return; } void leaves(Node* node){ if(node==NULL)return; if(!node->left and !node->right) ans.push_back(node->data); leaves(node->left); leaves(node->right); } void righttree(Node* root){ if(!root->left and !root->right)return; ans.push_back(root->data); if(root->right!=NULL and (root->right->left or root->right->right)) righttree(root->right); if(root->left!=NULL and root->right==NULL) righttree(root->left); return; } };
@nishchaygupta9988
@nishchaygupta9988 2 жыл бұрын
Is isLeaf() in STL or we have to write the code explicitly ? I have checked on the internet there is no such inbuilt function for it. Please someone solve this query.
@plsgivemecat
@plsgivemecat Жыл бұрын
Explicitly. It's hardly 2 lines. def isLeaf(self,node): if not node.left and not node.right: return True
@nishchaygupta9988
@nishchaygupta9988 Жыл бұрын
@@plsgivemecat Thanks Buddy 💯
@shreyasvishwakarma8979
@shreyasvishwakarma8979 3 жыл бұрын
Its a really GREAT GREAT && the BEST tree series! Nice Work STRIVER. Keep it up!
@naveen_kotha
@naveen_kotha 3 жыл бұрын
Try to make series on Recursion, Dynamic Programming also
@amitarya4894
@amitarya4894 Ай бұрын
Thank you
@NoName-hd7ok
@NoName-hd7ok 4 ай бұрын
Do inorder and not level order traversal for leaves
@dinakarrajkotipalli2250
@dinakarrajkotipalli2250 8 ай бұрын
what would be the boundary traversal for a binary tree only having root node ..as if there was only one root node according to explanation boundary traversal was empty.is it correct? dont we get our root node included in its boundary traversal if root node was only leaf node
@supratimbhattacharjee5324
@supratimbhattacharjee5324 3 жыл бұрын
Why inorder for leaf nodes? We can also do preorder traversal as this will also give leaf nodes from left to right.
@takeUforward
@takeUforward 3 жыл бұрын
Yeah read pinned comment..
@ashishharshvardhan4580
@ashishharshvardhan4580 3 жыл бұрын
Hey, hope your health is alright. It must be something serious that you were not able to upload all I thought. Take Care! And thank you for your classes.
@arzooqureshi8821
@arzooqureshi8821 10 ай бұрын
Striver, Please add heaps videos too 🥺
@iamparitosh
@iamparitosh 3 жыл бұрын
Awesome! using it for problems links really good selection striver!!
@saqibaqeel9196
@saqibaqeel9196 3 ай бұрын
can we solve using line concept???
@avadheshsingh4255
@avadheshsingh4255 3 жыл бұрын
what an explanation great as always
@amrithapatil4595
@amrithapatil4595 3 жыл бұрын
Will this logic work for the following tree? 1 / \ 2 8 \ 3 / \ 4 5 / 6 / 7 According to the explained approach, leftBoundary: [1,2,3] (excluding leaf nodes) leaf: [4,7] rightBoundary: [8] result: [1,2,3,4,7,8] But the correct answer should be [1,2,3,4,6,7,8]
@anmoldua9755
@anmoldua9755 3 жыл бұрын
Yes, that's what i was thinking too(But may be it is not included in the boundary as its inner nodee) result: [1,2,3,4,7,8] But the correct answer should be [1,2,3,4,6,7,8] I think result would be the correct answer as consider boundary(imagine boundary as outer boundary or circle outer circumfrance)
@takeUforward
@takeUforward 3 жыл бұрын
Yes anmol
@AniketSomwanshi-ll7mz
@AniketSomwanshi-ll7mz 3 жыл бұрын
According to this logic, 5 should also be there in the right view innit?
@pranavsharma7479
@pranavsharma7479 2 жыл бұрын
@@anmoldua9755 but 8 will not be covered in the code written right?
@utkarshsharma6650
@utkarshsharma6650 2 жыл бұрын
@@pranavsharma7479 why not?
@adebisisheriff159
@adebisisheriff159 10 ай бұрын
Thanks Bhaiya!!!!!!
@supratimbhattacharjee5324
@supratimbhattacharjee5324 2 жыл бұрын
class Solution { public: void leftBound(Node* root, vector& ans, Node* realRoot) { if(!root) return; if(!realRoot->left) { ans.push_back(root->data); return; } if(!root->left && !root->right) return; ans.push_back(root->data); if(root->left) leftBound(root->left,ans,realRoot); else leftBound(root->right,ans,realRoot); } void appendLeaf(Node* root, vector& ans, Node* &lastLeafRef) { if(!root) return; if(!root->left && !root->right) { lastLeafRef=root; ans.push_back(root->data); } appendLeaf(root->left, ans, lastLeafRef); appendLeaf(root->right, ans, lastLeafRef); } void rightBound(Node* root, vector& ans, Node* lastLeafRef, Node* realRoot) { if(!root) return; if(!realRoot->right) return; if(root->right) rightBound(root->right,ans,lastLeafRef,realRoot); else rightBound(root->left,ans,lastLeafRef,realRoot); if(root!=realRoot && root!=lastLeafRef) ans.push_back(root->data); } vector boundary(Node *root) { vector ans; Node* lastLeafRef=nullptr; if(!root) return ans; leftBound(root, ans, root); appendLeaf(root, ans, lastLeafRef); rightBound(root, ans, lastLeafRef, root); return ans; } };
@yashkhatwani3198
@yashkhatwani3198 2 жыл бұрын
Thank you Bhaiya, Good explanation
@RaviKumar-jv9es
@RaviKumar-jv9es 3 жыл бұрын
Bhaiya I have watched till here... waiting for another videos of this series
L21. Vertical Order Traversal of Binary Tree | C++ | Java
18:53
take U forward
Рет қаралды 335 М.
Муж внезапно вернулся домой @Oscar_elteacher
00:43
История одного вокалиста
Рет қаралды 6 МЛН
Perfect Pitch Challenge? Easy! 🎤😎| Free Fire Official
00:13
Garena Free Fire Global
Рет қаралды 100 МЛН
Why no RONALDO?! 🤔⚽️
00:28
Celine Dept
Рет қаралды 54 МЛН
L27. Lowest Common Ancestor in Binary Tree | LCA | C++ | Java
14:09
take U forward
Рет қаралды 327 М.
Could TIME Really Be an Illusion?
15:36
Arvin Ash
Рет қаралды 61 М.
I Added an AI to My Minecraft Server - Nobody Realised…
21:39
TheMisterEpic
Рет қаралды 7 М.
L24. Right/Left View of Binary Tree | C++ | Java
13:28
take U forward
Рет қаралды 228 М.
L17. Maximum Path Sum in Binary Tree | C++ | Java
17:50
take U forward
Рет қаралды 362 М.
LeetCode was HARD until I Learned these 15 Patterns
13:00
Ashish Pratap Singh
Рет қаралды 577 М.
Муж внезапно вернулся домой @Oscar_elteacher
00:43
История одного вокалиста
Рет қаралды 6 МЛН